iDev: UIImage and UIImage View

When we use images in our application then we face different type of scenarios while handling the image. Before we go into the scenarios / situations of image handling in Application, let us understand the concept of UIImage and UIImageView.

Concept of UIImage and UIImageView (container)

UIImage – Bitmap with different formats Ex png and jpeg. Recommended format is png.UIImageView – This is an iOS Widget that acts like a container for holding the image. To hold the image, UIImageView is required.

When UIImage is shown in UIImageView, there is a property (Content Mode) of UIImageView, that render the Image in UIImageView. We mostly use three types of Content Mode property. These are:

  • Scale To Fill
  • Aspect Fit
  • Aspect Fill

How these Content Mode render the image we can see by following examples

  • UIImage of size (100×150)
  • UIImageView of size (200×200)

Different Content modes for placing Image in ImageView

1. Scale To Fill

In this case, content is scaled to fill in ImageView with distorted or same aspect ratio. If the image aspect ratio is different than that of container then final image ratio when fitted in the container will be different and hence the image is finally distorted.

(Aspect Ratio is Width / Height)

InnovationM Image Handling in iOS

2. Aspect Fit

In this case, content is scaled to fit in ImageView (container) without changing the aspect ratio of image . Remainder is transparent.

InnovationM Image Handling in iOS

3. Aspect Fill Without Clipping

In this case, image is scaled to fill in ImageView. Aspect ratio of image is not changed.

InnovationM Image Handling in iOS

4. Aspect Fill With Clipping

In this case, content is scaled to fill in ImageView the same way it happen in the above case but then finally image is cropped to the exact size of the ImageView size.

InnovationM Image Handling in iOS

Calculating new width and height with maintaining aspect ratio

Image original width = 100 and height = 150
Container width  = 200 and height = 200

x-ratio = Container width / Image original width = 200/100 = 2.0
y-ratio =  Container height / Image original height = 200/ 150 =  1.33

Selected ratio = min (x-ratio, y-ratio) = 1.33

Final Image width = Image original width * Selected Ratio = 100 * 1.33 = 133
Final Image height = Image original height * Selected Ratio = 150 * 1.33 = 200

Final Image width x height = 133 x 200 (Original width x height of image was 100 x 150)

Showing Images coming from Server (Different Scenarios)

We can use Aspect Fit mode for all the scenarios. It will serve in every scenario if you don’t want to distort image.

Scenario 1
Image width is lesser than Container width.
Image height is lesser than Container height

Image width = 100 and height = 150
UIImageView width = 200 and height = 200

Final Image width = 133  and height = 200 (Refer the calculations above)
Image is scaled up to fit the container.

InnovationM Image Handling in iOS

Scenario 2 
Image width is greater than Container width.
Image height is lesser than Container height

Image width = 100 and height = 150
UIImageView width = 80 and height = 200

Final Image width = 80 and height = 122
Image is scaled down to fit the container.

InnovationM Image Handling in iOS

Scenario 3
Image width is lesser than Container width.
Image height is greater than Container height.

Image width = 100 and height = 150
UIImageView width = 200 and height = 120

Final width = 80  and height = 120
Image is scaled down to fit the container.
InnovationM Image Handling in iOS

Scenario 4
Image width is greater than Container width.
Image height is greater than Container height.

Image width = 100 and height = 150
UIImageView width = 80 and height = 100

Final width = 66  and height = 100
Image is scaled down to fit the container.

InnovationM Image Handling in iOS

Scenario 5 (Same Aspect Ratio of Image and ImageView)
Image width is greater than Container width.
Image height is greater than Container height.

Image width = 100 and height = 150
UIImageView width = 80 and height = 120

Final width = 80 and height = 120
Image is scaled down to fit the container.

InnovationM Image Handling in iOS

Scenario 6 (Same Aspect Ratio of Image and ImageView)
Image width is lesser than Container width.
Image height is lesser than Container height.

Image width = 100 and height = 150
UIImageView width = 120 and height = 180

Final width = 120 and height = 180
Image is scaled up to fit the container.

InnovationM Image Handling in iOS

How we change the image size and compress image file size-

Uploading Images to the Server (Different Scenarios)

Many times we have to upload images in an application from device (iPhone, iPad) to the server. It could be a photo clicked from the camera or there was an old image that we choose and upload from the application.

Before uploading we can do two things with the image:

1. Change the width and height of original image.
2. Compress the image to be of smaller file size.

Let us understand them.

1. Change the width and height of original image.

To resize the image, we have to configure the drawing environment for rendering into a bitmap.

1# UIGraphicsBeginImageContextWithOptions()  method is used to create the bitmap-based graphics context.

This method takes two parameters:

  1. Size of image (changed size) and
  2. Scale factor of device as parameter.

Scale factor for Normal Display = 1.0
Scale factor for Retina Display = 2.0

2# – (void) drawInRect:(CGRect)rect; method is used to draw the image in target rectangle.

3# UIGraphicsGetImageFromCurrentImageContext()  method is used to get the resized image from drawing environment.

4# UIGraphicsEndImageContext() method is used to clean up the bitmap drawing environment and remove the graphics context from the top of the context stack.

Example :

Original source Image  Size = (2448, 3264)
Original source image file size = 3.8 MB

After resizing image to size (1024,768):
Resized source Image  Size = (1024,768)
Resized source image file size = 2.0 MB

Code Example:

2. Compress the image to be of smaller file size.

We can compress the image file size by following method.

UIImageJPEGRepresentation() This method takes two parameter

  1. UIImage object.
  2. Compress ratio (It can be between 0.0 and 1.0)

This method will return NSData representation of image after compressing.

Example :

Original source Image  Size = (2448, 3264)
Original source image file size = 3.8 MB

After compressing image file  size by 0.5:
Resized source Image  Size = (2448, 3264)
Resized source image file size = 534 KB

Code Example:

Depending upon your requirement whether to reduce the size (width and height in pixels) OR reduce the file size OR Both, you may apply the above.

Original Source: Click Here

iDev: Set Warnings in Xcode

Here a reference docs, How we set the warnings in Xcode and get the results :

Source Link: Click Here

Warnings are diagnostic messages that report constructions that are not inherently erroneous but that are risky or suggest there may have been an error.

The following language-independent options do not enable specific warnings but control the kinds of diagnostics produced by GCC.

Check the code for syntax errors, but don’t do anything beyond that.
Limits the maximum number of error messages to n, at which point GCC bails out rather than attempting to continue processing the source code. If n is 0 (the default), there is no limit on the number of error messages produced. If -Wfatal-errors is also specified, then -Wfatal-errors takes precedence over this option.
Inhibit all warning messages.
Make all warnings into errors.
Make the specified warning into an error. The specifier for a warning is appended; for example -Werror=switch turns the warnings controlled by -Wswitch into errors. This switch takes a negative form, to be used to negate -Werror for specific warnings; for example -Wno-error=switch makes -Wswitch warnings not be errors, even when -Werror is in effect.The warning message for each controllable warning includes the option that controls the warning. That option can then be used with -Werror= and -Wno-error= as described above. (Printing of the option in the warning message can be disabled using the -fno-diagnostics-show-option flag.)

Note that specifying -Werror=foo automatically implies -Wfoo. However, -Wno-error=foo does not imply anything.

This option causes the compiler to abort compilation on the first error occurred rather than trying to keep going and printing further error messages.

You can request many specific warnings with options beginning with ‘-W’, for example -Wimplicit to request warnings on implicit declarations. Each of these specific warning options also has a negative form beginning ‘-Wno-’ to turn off warnings; for example, -Wno-implicit. This manual lists only one of the two forms, whichever is not the default. For further language-specific options also refer to C++ Dialect Options and Objective-C and Objective-C++ Dialect Options.

Some options, such as -Wall and -Wextra, turn on other options, such as -Wunused, which may turn on further options, such as -Wunused-value. The combined effect of positive and negative forms is that more specific options have priority over less specific ones, independently of their position in the command-line. For options of the same specificity, the last one takes effect. Options enabled or disabled via pragmas (see Diagnostic Pragmas) take effect as if they appeared at the end of the command-line.

When an unrecognized warning option is requested (e.g., -Wunknown-warning), GCC emits a diagnostic stating that the option is not recognized. However, if the -Wno- form is used, the behavior is slightly different: no diagnostic is produced for -Wno-unknown-warning unless other diagnostics are being produced. This allows the use of new -Wno- options with old compilers, but if something goes wrong, the compiler warns that an unrecognized option is present.

Issue all the warnings demanded by strict ISO C and ISO C++; reject all programs that use forbidden extensions, and some other programs that do not follow ISO C and ISO C++. For ISO C, follows the version of the ISO C standard specified by any -std option used.Valid ISO C and ISO C++ programs should compile properly with or without this option (though a rare few require -ansi or a -std option specifying the required version of ISO C). However, without this option, certain GNU extensions and traditional C and C++ features are supported as well. With this option, they are rejected.

-Wpedantic does not cause warning messages for use of the alternate keywords whose names begin and end with ‘__’. Pedantic warnings are also disabled in the expression that follows __extension__. However, only system header files should use these escape routes; application programs should avoid them. See Alternate Keywords.

Some users try to use -Wpedantic to check programs for strict ISO C conformance. They soon find that it does not do quite what they want: it finds some non-ISO practices, but not all—only those for which ISO C requires a diagnostic, and some others for which diagnostics have been added.

A feature to report any failure to conform to ISO C might be useful in some instances, but would require considerable additional work and would be quite different from -Wpedantic. We don’t have plans to support such a feature in the near future.

Where the standard specified with -std represents a GNU extended dialect of C, such as ‘gnu90’ or ‘gnu99’, there is a corresponding base standard, the version of ISO C on which the GNU extended dialect is based. Warnings from -Wpedantic are given where they are required by the base standard. (It does not make sense for such warnings to be given only for features not in the specified GNU C dialect, since by definition the GNU dialects of C include all features the compiler supports with the given option, and there would be nothing to warn about.)

Give an error whenever the base standard (see -Wpedantic) requires a diagnostic, in some cases where there is undefined behavior at compile-time and in some other cases that do not prevent compilation of programs that are valid according to the standard. This is not equivalent to -Werror=pedantic, since there are errors enabled by this option and not enabled by the latter and vice versa.
This enables all the warnings about constructions that some users consider questionable, and that are easy to avoid (or modify to prevent the warning), even in conjunction with macros. This also enables some language-specific warnings described in C++ Dialect Options and Objective-C and Objective-C++ Dialect Options.-Wall turns on the following warning flags:

          -Warray-bounds=1 (only with -O2)  
          -Wc++11-compat  -Wc++14-compat
          -Wenum-compare (in C/ObjC; this is on by default in C++) 
          -Wimplicit-int (C and Objective-C only) 
          -Wimplicit-function-declaration (C and Objective-C only) 
          -Wmain (only for C/ObjC and unless -ffreestanding)  
          -Wmissing-braces (only for C/ObjC) 
          -Wsign-compare (only in C++)  

Note that some warning flags are not implied by -Wall. Some of them warn about constructions that users generally do not consider questionable, but which occasionally you might wish to check for; others warn about constructions that are necessary or hard to avoid in some cases, and there is no simple way to modify the code to suppress the warning. Some of them are enabled by -Wextra but many of them must be enabled individually.

This enables some extra warning flags that are not enabled by -Wall. (This option used to be called -W. The older name is still supported, but the newer name is more descriptive.)

          -Wmissing-parameter-type (C only)  
          -Wold-style-declaration (C only)  
          -Wunused-parameter (only with -Wunused or -Wall) 
          -Wunused-but-set-parameter (only with -Wunused or -Wall)  

The option -Wextra also prints warning messages for the following cases:

  • A pointer is compared against integer zero with <, <=, >, or >=.
  • (C++ only) An enumerator and a non-enumerator both appear in a conditional expression.
  • (C++ only) Ambiguous virtual bases.
  • (C++ only) Subscripting an array that has been declared register.
  • (C++ only) Taking the address of a variable that has been declared register.
  • (C++ only) A base class is not initialized in a derived class’s copy constructor.
Warn if an array subscript has type char. This is a common cause of error, as programmers often forget that this type is signed on some machines. This warning is enabled by -Wall.
Warn whenever a comment-start sequence ‘/*’ appears in a ‘/*’ comment, or whenever a Backslash-Newline appears in a ‘//’ comment. This warning is enabled by -Wall.
Warn if feedback profiles do not match when using the -fprofile-use option. If a source file is changed between compiling with -fprofile-gen and with -fprofile-use, the files with the profile feedback can fail to match the source file and GCC cannot use the profile feedback information. By default, this warning is enabled and is treated as an error. -Wno-coverage-mismatch can be used to disable the warning or -Wno-error=coverage-mismatch can be used to disable the error. Disabling the error for this warning can result in poorly optimized code and is useful only in the case of very minor changes such as bug fixes to an existing code-base. Completely disabling the warning is not recommended.
(C, Objective-C, C++, Objective-C++ and Fortran only)Suppress warning messages emitted by #warning directives.

-Wdouble-promotion (C, C++, Objective-C and Objective-C++ only)
Give a warning when a value of type float is implicitly promoted to double. CPUs with a 32-bit “single-precision” floating-point unit implement float in hardware, but emulatedouble in software. On such a machine, doing computations using double values is much more expensive because of the overhead required for software emulation.It is easy to accidentally do computations with double because floating-point literals are implicitly of type double. For example, in:

          float area(float radius)
             return 3.14159 * radius * radius;

the compiler performs the entire computation with double because the floating-point literal is a double.

Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense. This includes standard functions, and others specified by format attributes (see Function Attributes), in the printf, scanf, strftime and strfmon (an X/Open extension, not in the C standard) families (or other target-specific families). Which functions are checked without format attributes having been specified depends on the standard version selected, and such checks of functions without the attribute specified are disabled by -ffreestanding or -fno-builtin.The formats are checked against the format features supported by GNU libc version 2.2. These include all ISO C90 and C99 features, as well as features from the Single Unix Specification and some BSD and GNU extensions. Other library implementations may not support all these features; GCC does not support warning about features that go beyond a particular library’s limitations. However, if -Wpedantic is used with -Wformat, warnings are given about format features not in the selected standard version (but not for strfmonformats, since those are not in any version of the C standard). See Options Controlling C Dialect.

Option -Wformat is equivalent to -Wformat=1, and -Wno-format is equivalent to -Wformat=0. Since -Wformat also checks for null format arguments for several functions, -Wformat also implies -Wnonnull. Some aspects of this level of format checking can be disabled by the options: -Wno-format-contains-nul, -Wno-format-extra-args, and -Wno-format-zero-length. -Wformat is enabled by -Wall.
If -Wformat is specified, do not warn about format strings that contain NUL bytes.
If -Wformat is specified, do not warn about excess arguments to a printf or scanf format function. The C standard specifies that such arguments are ignored.Where the unused arguments lie between used arguments that are specified with ‘$’ operand number specifications, normally warnings are still given, since the implementation could not know what type to pass to va_arg to skip the unused arguments. However, in the case of scanf formats, this option suppresses the warning if the unused arguments are all pointers, since the Single Unix Specification says that such unused arguments are allowed.

If -Wformat is specified, do not warn about zero-length formats. The C standard specifies that zero-length formats are allowed.
Enable -Wformat plus additional format checks. Currently equivalent to -Wformat -Wformat-nonliteral -Wformat-security -Wformat-y2k.
If -Wformat is specified, also warn if the format string is not a string literal and so cannot be checked, unless the format function takes its format arguments as a va_list.
If -Wformat is specified, also warn about uses of format functions that represent possible security problems. At present, this warns about calls to printf and scanf functions where the format string is not a string literal and there are no format arguments, as in printf (foo);. This may be a security hole if the format string came from untrusted input and contains ‘%n’. (This is currently a subset of what -Wformat-nonliteral warns about, but in future warnings may be added to -Wformat-security that are not included in -Wformat-nonliteral.)
If -Wformat is specified, also warn if the format string requires an unsigned argument and the argument is signed and vice versa.
If -Wformat is specified, also warn about strftime formats that may yield only a two-digit year.
Warn about passing a null pointer for arguments marked as requiring a non-null value by the nonnull function attribute.Also warns when comparing an argument marked with the nonnull function attribute against null inside the function.

-Wnonnull is included in -Wall and -Wformat. It can be disabled with the -Wno-nonnull option.

Warn if the compiler detects paths that trigger erroneous or undefined behavior due to dereferencing a null pointer. This option is only active when -fdelete-null-pointer-checksis active, which is enabled by optimizations in most targets. The precision of the warnings depends on the optimization options used.
-Winit-self (C, C++, Objective-C and Objective-C++ only)
Warn about uninitialized variables that are initialized with themselves. Note this option can only be used with the -Wuninitialized option.For example, GCC warns about i being uninitialized in the following snippet only when -Winit-self has been specified:

          int f()
            int i = i;
            return i;

This warning is enabled by -Wall in C++.

-Wimplicit-int (C and Objective-C only)
Warn when a declaration does not specify a type. This warning is enabled by -Wall.
-Wimplicit-function-declaration (C and Objective-C only)
Give a warning whenever a function is used before being declared. In C99 mode (-std=c99 or -std=gnu99), this warning is enabled by default and it is made into an error by -pedantic-errors. This warning is also enabled by -Wall.
-Wimplicit (C and Objective-C only)
Same as -Wimplicit-int and -Wimplicit-function-declaration. This warning is enabled by -Wall.
-Wignored-qualifiers (C and C++ only)
Warn if the return type of a function has a type qualifier such as const. For ISO C such a type qualifier has no effect, since the value returned by a function is not an lvalue. For C++, the warning is only emitted for scalar types or void. ISO C prohibits qualified void return types on function definitions, so such return types always receive a warning even without this option.This warning is also enabled by -Wextra.

Warn if the type of main is suspicious. main should be a function with external linkage, returning int, taking either zero arguments, two, or three arguments of appropriate types. This warning is enabled by default in C++ and is enabled by either -Wall or -Wpedantic.
-Wmisleading-indentation (C and C++ only)
Warn when the indentation of the code does not reflect the block structure. Specifically, a warning is issued for if, else, while, and for clauses with a guarded statement that does not use braces, followed by an unguarded statement with the same indentation.This warning is disabled by default.

In the following example, the call to “bar” is misleadingly indented as if it were guarded by the “if” conditional.

            if (some_condition ())
              foo ();
              bar ();  /* Gotcha: this is not guarded by the "if".  */

In the case of mixed tabs and spaces, the warning uses the -ftabstop= option to determine if the statements line up (defaulting to 8).

The warning is not issued for code involving multiline preprocessor logic such as the following example.

            if (flagA)
              foo (0);
            if (flagB)
              foo (1);

The warning is not issued after a #line directive, since this typically indicates autogenerated code, and no assumptions can be made about the layout of the file that the directive references.

Warn if an aggregate or union initializer is not fully bracketed. In the following example, the initializer for a is not fully bracketed, but that for b is fully bracketed. This warning is enabled by -Wall in C.

          int a[2][2] = { 0, 1, 2, 3 };
          int b[2][2] = { { 0, 1 }, { 2, 3 } };

This warning is enabled by -Wall.

-Wmissing-include-dirs (C, C++, Objective-C and Objective-C++ only)
Warn if a user-supplied include directory does not exist.
Warn if parentheses are omitted in certain contexts, such as when there is an assignment in a context where a truth value is expected, or when operators are nested whose precedence people often get confused about.Also warn if a comparison like x<=y<=z appears; this is equivalent to (x<=y ? 1 : 0) <= z, which is a different interpretation from that of ordinary mathematical notation.

Also warn about constructions where there may be confusion to which if statement an else branch belongs. Here is an example of such a case:

            if (a)
              if (b)
                foo ();
              bar ();

In C/C++, every else branch belongs to the innermost possible if statement, which in this example is if (b). This is often not what the programmer expected, as illustrated in the above example by indentation the programmer chose. When there is the potential for this confusion, GCC issues a warning when this flag is specified. To eliminate the warning, add explicit braces around the innermost if statement so there is no way the else can belong to the enclosing if. The resulting code looks like this:

            if (a)
                if (b)
                  foo ();
                  bar ();

Also warn for dangerous uses of the GNU extension to ?: with omitted middle operand. When the condition in the ?: operator is a boolean expression, the omitted value is always 1. Often programmers expect it to be a value computed inside the conditional expression instead.

This warning is enabled by -Wall.

Warn about code that may have undefined semantics because of violations of sequence point rules in the C and C++ standards.The C and C++ standards define the order in which expressions in a C/C++ program are evaluated in terms of sequence points, which represent a partial ordering between the execution of parts of the program: those executed before the sequence point, and those executed after it. These occur after the evaluation of a full expression (one which is not part of a larger expression), after the evaluation of the first operand of a &&, ||, ? : or , (comma) operator, before a function is called (but after the evaluation of its arguments and the expression denoting the called function), and in certain other places. Other than as expressed by the sequence point rules, the order of evaluation of subexpressions of an expression is not specified. All these rules describe only a partial order rather than a total order, since, for example, if two functions are called within one expression with no sequence point between them, the order in which the functions are called is not specified. However, the standards committee have ruled that function calls do not overlap.

It is not specified when between sequence points modifications to the values of objects take effect. Programs whose behavior depends on this have undefined behavior; the C and C++ standards specify that “Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.”. If a program breaks these rules, the results on any particular implementation are entirely unpredictable.

Examples of code with undefined behavior are a = a++;, a[n] = b[n++] and a[i++] = i;. Some more complicated cases are not diagnosed by this option, and it may give an occasional false positive result, but in general it has been found fairly effective at detecting this sort of problem in programs.

The standard is worded confusingly, therefore there is some debate over the precise meaning of the sequence point rules in subtle cases. Links to discussions of the problem, including proposed formal definitions, may be found on the GCC readings page, at

This warning is enabled by -Wall for C and C++.

Do not warn about returning a pointer (or in C++, a reference) to a variable that goes out of scope after the function returns.
Warn whenever a function is defined with a return type that defaults to int. Also warn about any return statement with no return value in a function whose return type is not void(falling off the end of the function body is considered returning without a value), and about a return statement with an expression in a function whose return type is void.For C++, a function without return type always produces a diagnostic message, even when -Wno-return-type is specified. The only exceptions are main and functions defined in system headers.

This warning is enabled by -Wall.

Warn if shift count is negative. This warning is enabled by default.
Warn if shift count >= width of type. This warning is enabled by default.
Warn if left shifting a negative value. This warning is enabled by -Wextra in C99 and C++11 modes (and newer).
Warn about left shift overflows. This warning is enabled by default in C99 and C++11 modes (and newer).

This is the warning level of -Wshift-overflow and is enabled by default in C99 and C++11 modes (and newer). This warning level does not warn about left-shifting 1 into the sign bit. (However, in C, such an overflow is still rejected in contexts where an integer constant expression is required.)
This warning level also warns about left-shifting 1 into the sign bit, unless C++14 mode is active.
Warn whenever a switch statement has an index of enumerated type and lacks a case for one or more of the named codes of that enumeration. (The presence of a default label prevents this warning.) case labels outside the enumeration range also provoke warnings when this option is used (even if there is a default label). This warning is enabled by -Wall.
Warn whenever a switch statement does not have a default case.
Warn whenever a switch statement has an index of enumerated type and lacks a case for one or more of the named codes of that enumeration. case labels outside the enumeration range also provoke warnings when this option is used. The only difference between -Wswitch and this option is that this option gives a warning about an omitted enumeration code even if there is a default label.
Warn whenever a switch statement has an index of boolean type and the case values are outside the range of a boolean type. It is possible to suppress this warning by casting the controlling expression to a type other than bool. For example:

          switch ((int) (a == 4))

This warning is enabled by default for C and C++ programs.

-Wsync-nand (C and C++ only)
Warn when __sync_fetch_and_nand and __sync_nand_and_fetch built-in functions are used. These functions changed semantics in GCC 4.4.
Warn if any trigraphs are encountered that might change the meaning of the program (trigraphs within comments are not warned about). This warning is enabled by -Wall.
Warn whenever a function parameter is assigned to, but otherwise unused (aside from its declaration).To suppress this warning use the unused attribute (see Variable Attributes).

This warning is also enabled by -Wunused together with -Wextra.

Warn whenever a local variable is assigned to, but otherwise unused (aside from its declaration). This warning is enabled by -Wall.To suppress this warning use the unused attribute (see Variable Attributes).

This warning is also enabled by -Wunused, which is enabled by -Wall.

Warn whenever a static function is declared but not defined or a non-inline static function is unused. This warning is enabled by -Wall.
Warn whenever a label is declared but not used. This warning is enabled by -Wall.To suppress this warning use the unused attribute (see Variable Attributes).

-Wunused-local-typedefs (C, Objective-C, C++ and Objective-C++ only)
Warn when a typedef locally defined in a function is not used. This warning is enabled by -Wall.
Warn whenever a function parameter is unused aside from its declaration.To suppress this warning use the unused attribute (see Variable Attributes).

Do not warn if a caller of a function marked with attribute warn_unused_result (see Function Attributes) does not use its return value. The default is -Wunused-result.
Warn whenever a local or static variable is unused aside from its declaration. This option implies -Wunused-const-variable for C, but not for C++. This warning is enabled by -Wall.To suppress this warning use the unused attribute (see Variable Attributes).

Warn whenever a constant static variable is unused aside from its declaration. This warning is enabled by -Wunused-variable for C, but not for C++. In C++ this is normally not an error since const variables take the place of #defines in C++.To suppress this warning use the unused attribute (see Variable Attributes).

Warn whenever a statement computes a result that is explicitly not used. To suppress this warning cast the unused expression to void. This includes an expression-statement or the left-hand side of a comma expression that contains no side effects. For example, an expression such as x[i,j] causes a warning, while x[(void)i,j] does not.This warning is enabled by -Wall.

All the above -Wunused options combined.In order to get a warning about an unused function parameter, you must either specify -Wextra -Wunused (note that -Wall implies -Wunused), or separately specify -Wunused-parameter.

Warn if an automatic variable is used without first being initialized or if a variable may be clobbered by a setjmp call. In C++, warn if a non-static reference or non-static constmember appears in a class without constructors.If you want to warn about code that uses the uninitialized value of the variable in its own initializer, use the -Winit-self option.

These warnings occur for individual uninitialized or clobbered elements of structure, union or array variables as well as for variables that are uninitialized or clobbered as a whole. They do not occur for variables or elements declared volatile. Because these warnings depend on optimization, the exact variables or elements for which there are warnings depends on the precise optimization options and version of GCC used.

Note that there may be no warning about a variable that is used only to compute a value that itself is never used, because such computations may be deleted by data flow analysis before the warnings are printed.

For an automatic variable, if there exists a path from the function entry to a use of the variable that is initialized, but there exist some other paths for which the variable is not initialized, the compiler emits a warning if it cannot prove the uninitialized paths are not executed at run time. These warnings are made optional because GCC is not smart enough to see all the reasons why the code might be correct in spite of appearing to have an error. Here is one example of how this can happen:

            int x;
            switch (y)
              case 1: x = 1;
              case 2: x = 4;
              case 3: x = 5;
            foo (x);

If the value of y is always 1, 2 or 3, then x is always initialized, but GCC doesn’t know this. To suppress the warning, you need to provide a default case with assert(0) or similar code.

This option also warns when a non-volatile automatic variable might be changed by a call to longjmp. These warnings as well are possible only in optimizing compilation.

The compiler sees only the calls to setjmp. It cannot know where longjmp will be called; in fact, a signal handler could call it at any point in the code. As a result, you may get a warning even when there is in fact no problem because longjmp cannot in fact be called at the place that would cause a problem.

Some spurious warnings can be avoided if you declare all the functions you use that never return as noreturn. See Function Attributes.

This warning is enabled by -Wall or -Wextra.

Warn when a #pragma directive is encountered that is not understood by GCC. If this command-line option is used, warnings are even issued for unknown pragmas in system header files. This is not the case if the warnings are only enabled by the -Wall command-line option.
Do not warn about misuses of pragmas, such as incorrect parameters, invalid syntax, or conflicts between pragmas. See also -Wunknown-pragmas.
This option is only active when -fstrict-aliasing is active. It warns about code that might break the strict aliasing rules that the compiler is using for optimization. The warning does not catch all cases, but does attempt to catch the more common pitfalls. It is included in -Wall. It is equivalent to -Wstrict-aliasing=3
This option is only active when -fstrict-aliasing is active. It warns about code that might break the strict aliasing rules that the compiler is using for optimization. Higher levels correspond to higher accuracy (fewer false positives). Higher levels also correspond to more effort, similar to the way -O works. -Wstrict-aliasing is equivalent to -Wstrict-aliasing=3.Level 1: Most aggressive, quick, least accurate. Possibly useful when higher levels do not warn but -fstrict-aliasing still breaks the code, as it has very few false negatives. However, it has many false positives. Warns for all pointer conversions between possibly incompatible types, even if never dereferenced. Runs in the front end only.

Level 2: Aggressive, quick, not too precise. May still have many false positives (not as many as level 1 though), and few false negatives (but possibly more than level 1). Unlike level 1, it only warns when an address is taken. Warns about incomplete types. Runs in the front end only.

Level 3 (default for -Wstrict-aliasing): Should have very few false positives and few false negatives. Slightly slower than levels 1 or 2 when optimization is enabled. Takes care of the common pun+dereference pattern in the front end: *(int*)&some_float. If optimization is enabled, it also runs in the back end, where it deals with multiple statement cases using flow-sensitive points-to information. Only warns when the converted pointer is dereferenced. Does not warn about incomplete types.

This option is only active when -fstrict-overflow is active. It warns about cases where the compiler optimizes based on the assumption that signed overflow does not occur. Note that it does not warn about all cases where the code might overflow: it only warns about cases where the compiler implements some optimization. Thus this warning depends on the optimization level.An optimization that assumes that signed overflow does not occur is perfectly safe if the values of the variables involved are such that overflow never does, in fact, occur. Therefore this warning can easily give a false positive: a warning about code that is not actually a problem. To help focus on important issues, several warning levels are defined. No warnings are issued for the use of undefined signed overflow when estimating how many iterations a loop requires, in particular when determining whether a loop will be executed at all.

Warn about cases that are both questionable and easy to avoid. For example, with -fstrict-overflow, the compiler simplifies x + 1 > x to 1. This level of -Wstrict-overflow is enabled by -Wall; higher levels are not, and must be explicitly requested.
Also warn about other cases where a comparison is simplified to a constant. For example: abs (x) >= 0. This can only be simplified when -fstrict-overflow is in effect, because abs (INT_MIN) overflows to INT_MIN, which is less than zero. -Wstrict-overflow (with no level) is the same as -Wstrict-overflow=2.
Also warn about other cases where a comparison is simplified. For example: x + 1 > 1 is simplified to x > 0.
Also warn about other simplifications not covered by the above cases. For example: (x * 10) / 5 is simplified to x * 2.
Also warn about cases where the compiler reduces the magnitude of a constant involved in a comparison. For example: x + 2 > y is simplified to x + 1 >= y. This is reported only at the highest warning level because this simplification applies to many comparisons, so this warning level gives a very large number of false positives.
Warn for cases where adding an attribute may be beneficial. The attributes currently supported are listed below.

Warn about functions that might be candidates for attributes pure, const or noreturn. The compiler only warns for functions visible in other compilation units or (in the case ofpure and const) if it cannot prove that the function returns normally. A function returns normally if it doesn’t contain an infinite loop or return abnormally by throwing, callingabort or trapping. This analysis requires option -fipa-pure-const, which is enabled by default at -O and higher. Higher optimization levels improve the accuracy of the analysis.
Warn about function pointers that might be candidates for format attributes. Note these are only possible candidates, not absolute ones. GCC guesses that function pointers withformat attributes that are used in assignment, initialization, parameter passing or return statements should have a corresponding format attribute in the resulting type. I.e. the left-hand side of the assignment or initialization, the type of the parameter variable, or the return type of the containing function respectively should also have a format attribute to avoid the warning.GCC also warns about function definitions that might be candidates for format attributes. Again, these are only possible candidates. GCC guesses that format attributes might be appropriate for any function that calls a function like vprintf or vscanf, but this might not always be the case, and some functions for which format attributes are appropriate may not be detected.

Warn about types with virtual methods where code quality would be improved if the type were declared with the C++11 final specifier, or, if possible, declared in an anonymous namespace. This allows GCC to more aggressively devirtualize the polymorphic calls. This warning is more effective with link time optimization, where the information about the class hierarchy graph is more complete.
Warn about virtual methods where code quality would be improved if the method were declared with the C++11 final specifier, or, if possible, its type were declared in an anonymous namespace or with the final specifier. This warning is more effective with link time optimization, where the information about the class hierarchy graph is more complete. It is recommended to first consider suggestions of -Wsuggest-final-types and then rebuild with new annotations.
Warn about overriding virtual functions that are not marked with the override keyword.
This option is only active when -ftree-vrp is active (default for -O2 and above). It warns about subscripts to arrays that are always out of bounds. This warning is enabled by -Wall.

This is the warning level of -Warray-bounds and is enabled by -Wall; higher levels are not, and must be explicitly requested.
This warning level also warns about out of bounds access for arrays at the end of a struct and for arrays accessed through pointers. This warning level may give a larger number of false positives and is deactivated by default.
Warn about boolean expression compared with an integer value different from true/false. For instance, the following comparison is always false:

          int n = 5;
          if ((n > 1) == 2) { ... }

This warning is enabled by -Wall.

Warn about duplicated conditions in an if-else-if chain. For instance, warn for the following code:

          if (p->q != NULL) { ... }
          else if (p->q != NULL) { ... }

This warning is enabled by -Wall.

Warn when the ‘__builtin_frame_address’ or ‘__builtin_return_address’ is called with an argument greater than 0. Such calls may return indeterminate values or crash the program. The warning is included in -Wall.
-Wno-discarded-qualifiers (C and Objective-C only)
Do not warn if type qualifiers on pointers are being discarded. Typically, the compiler warns if a const char * variable is passed to a function that takes a char * parameter. This option can be used to suppress such a warning.
-Wno-discarded-array-qualifiers (C and Objective-C only)
Do not warn if type qualifiers on arrays which are pointer targets are being discarded. Typically, the compiler warns if a const int (*)[] variable is passed to a function that takes aint (*)[] parameter. This option can be used to suppress such a warning.
-Wno-incompatible-pointer-types (C and Objective-C only)
Do not warn when there is a conversion between pointers that have incompatible types. This warning is for cases not covered by -Wno-pointer-sign, which warns for pointer argument passing or assignment with different signedness.
-Wno-int-conversion (C and Objective-C only)
Do not warn about incompatible integer to pointer and pointer to integer conversions. This warning is about implicit conversions; for explicit conversions the warnings -Wno-int-to-pointer-cast and -Wno-pointer-to-int-cast may be used.
Do not warn about compile-time integer division by zero. Floating-point division by zero is not warned about, as it can be a legitimate way of obtaining infinities and NaNs.
Print warning messages for constructs found in system header files. Warnings from system headers are normally suppressed, on the assumption that they usually do not indicate real problems and would only make the compiler output harder to read. Using this command-line option tells GCC to emit warnings from system headers as if they occurred in user code. However, note that using -Wall in conjunction with this option does not warn about unknown pragmas in system headers—for that, -Wunknown-pragmas must also be used.
Warn if a self-comparison always evaluates to true or false. This warning detects various mistakes such as:

          int i = 1;
          if (i > i) { ... }

This warning is enabled by -Wall.

Warn about trampolines generated for pointers to nested functions. A trampoline is a small piece of data or code that is created at run time on the stack when the address of a nested function is taken, and is used to call the nested function indirectly. For some targets, it is made up of data only and thus requires no special treatment. But, for most targets, it is made up of code and thus requires the stack to be made executable in order for the program to work properly.
Warn if floating-point values are used in equality comparisons.The idea behind this is that sometimes it is convenient (for the programmer) to consider floating-point values as approximations to infinitely precise real numbers. If you are doing this, then you need to compute (by analyzing the code, or in some other way) the maximum or likely maximum error that the computation introduces, and allow for it when performing comparisons (and when producing output, but that’s a different problem). In particular, instead of testing for equality, you should check to see whether the two values have ranges that overlap; and this is done with the relational operators, so equality comparisons are probably mistaken.

-Wtraditional (C and Objective-C only)
Warn about certain constructs that behave differently in traditional and ISO C. Also warn about ISO C constructs that have no traditional C equivalent, and/or problematic constructs that should be avoided.

  • Macro parameters that appear within string literals in the macro body. In traditional C macro replacement takes place within string literals, but in ISO C it does not.
  • In traditional C, some preprocessor directives did not exist. Traditional preprocessors only considered a line to be a directive if the ‘#’ appeared in column 1 on the line. Therefore -Wtraditional warns about directives that traditional C understands but ignores because the ‘#’ does not appear as the first character on the line. It also suggests you hide directives like #pragma not understood by traditional C by indenting them. Some traditional implementations do not recognize #elif, so this option suggests avoiding it altogether.
  • A function-like macro that appears without arguments.
  • The unary plus operator.
  • The ‘U’ integer constant suffix, or the ‘F’ or ‘L’ floating-point constant suffixes. (Traditional C does support the ‘L’ suffix on integer constants.) Note, these suffixes appear in macros defined in the system headers of most modern systems, e.g. the ‘_MIN’/‘_MAX’ macros in <limits.h>. Use of these macros in user code might normally lead to spurious warnings, however GCC’s integrated preprocessor has enough context to avoid warning in these cases.
  • A function declared external in one block and then used after the end of the block.
  • A switch statement has an operand of type long.
  • A non-static function declaration follows a static one. This construct is not accepted by some traditional C compilers.
  • The ISO type of an integer constant has a different width or signedness from its traditional type. This warning is only issued if the base of the constant is ten. I.e. hexadecimal or octal values, which typically represent bit patterns, are not warned about.
  • Usage of ISO string concatenation is detected.
  • Initialization of automatic aggregates.
  • Identifier conflicts with labels. Traditional C lacks a separate namespace for labels.
  • Initialization of unions. If the initializer is zero, the warning is omitted. This is done under the assumption that the zero initializer in user code appears conditioned on e.g.__STDC__ to avoid missing initializer warnings and relies on default initialization to zero in the traditional C case.
  • Conversions by prototypes between fixed/floating-point values and vice versa. The absence of these prototypes when compiling with traditional C causes serious problems. This is a subset of the possible conversion warnings; for the full set use -Wtraditional-conversion.
  • Use of ISO C style function definitions. This warning intentionally is not issued for prototype declarations or variadic functions because these ISO C features appear in your code when using libiberty’s traditional C compatibility macros, PARAMS and VPARAMS. This warning is also bypassed for nested functions because that feature is already a GCC extension and thus not relevant to traditional C compatibility.
-Wtraditional-conversion (C and Objective-C only)
Warn if a prototype causes a type conversion that is different from what would happen to the same argument in the absence of a prototype. This includes conversions of fixed point to floating and vice versa, and conversions changing the width or signedness of a fixed-point argument except when the same as the default promotion.
-Wdeclaration-after-statement (C and Objective-C only)
Warn when a declaration is found after a statement in a block. This construct, known from C++, was introduced with ISO C99 and is by default allowed in GCC. It is not supported by ISO C90. See Mixed Declarations.
Warn if an undefined identifier is evaluated in an #if directive.
Do not warn whenever an #else or an #endif are followed by text.
Warn whenever a local variable or type declaration shadows another variable, parameter, type, class member (in C++), or instance variable (in Objective-C) or whenever a built-in function is shadowed. Note that in C++, the compiler warns if a local variable shadows an explicit typedef, but not if it shadows a struct/class/enum.
-Wno-shadow-ivar (Objective-C only)
Do not warn whenever a local variable shadows an instance variable in an Objective-C method.
Warn whenever an object of larger than len bytes is defined.
Warn if the size of a function frame is larger than len bytes. The computation done to determine the stack frame size is approximate and not conservative. The actual requirements may be somewhat greater than len even if you do not get a warning. In addition, any space allocated via alloca, variable-length arrays, or related constructs is not included by the compiler when determining whether or not to issue a warning.
Do not warn when attempting to free an object that was not allocated on the heap.
Warn if the stack usage of a function might be larger than len bytes. The computation done to determine the stack usage is conservative. Any space allocated via alloca, variable-length arrays, or related constructs is included by the compiler when determining whether or not to issue a warning.The message is in keeping with the output of -fstack-usage.

  • If the stack usage is fully static but exceeds the specified amount, it’s:
                     warning: stack usage is 1120 bytes
  • If the stack usage is (partly) dynamic but bounded, it’s:
                     warning: stack usage might be 1648 bytes
  • If the stack usage is (partly) dynamic and not bounded, it’s:
                     warning: stack usage might be unbounded
Warn if the loop cannot be optimized because the compiler cannot assume anything on the bounds of the loop indices. With -funsafe-loop-optimizations warn if the compiler makes such assumptions.
-Wno-pedantic-ms-format (MinGW targets only)
When used in combination with -Wformat and -pedantic without GNU extensions, this option disables the warnings about non-ISO printf / scanf format width specifiers I32, I64, and I used on Windows targets, which depend on the MS runtime.
Warn about placement new expressions with undefined behavior, such as constructing an object in a buffer that is smaller than the type of the object.
Warn about anything that depends on the “size of” a function type or of void. GNU C assigns these types a size of 1, for convenience in calculations with void * pointers and pointers to functions. In C++, warn also when an arithmetic operation involves NULL. This warning is also enabled by -Wpedantic.
Warn if a comparison is always true or always false due to the limited range of the data type, but do not warn for constant expressions. For example, warn if an unsigned variable is compared against zero with < or >=. This warning is also enabled by -Wextra.
-Wbad-function-cast (C and Objective-C only)
Warn when a function call is cast to a non-matching type. For example, warn if a call to a function returning an integer type is cast to a pointer type.
-Wc90-c99-compat (C and Objective-C only)
Warn about features not present in ISO C90, but present in ISO C99. For instance, warn about use of variable length arrays, long long type, bool type, compound literals, designated initializers, and so on. This option is independent of the standards mode. Warnings are disabled in the expression that follows __extension__.
-Wc99-c11-compat (C and Objective-C only)
Warn about features not present in ISO C99, but present in ISO C11. For instance, warn about use of anonymous structures and unions, _Atomic type qualifier, _Thread_localstorage-class specifier, _Alignas specifier, Alignof operator, _Generic keyword, and so on. This option is independent of the standards mode. Warnings are disabled in the expression that follows __extension__.
-Wc++-compat (C and Objective-C only)
Warn about ISO C constructs that are outside of the common subset of ISO C and ISO C++, e.g. request for implicit conversion from void * to a pointer to non-void type.
-Wc++11-compat (C++ and Objective-C++ only)
Warn about C++ constructs whose meaning differs between ISO C++ 1998 and ISO C++ 2011, e.g., identifiers in ISO C++ 1998 that are keywords in ISO C++ 2011. This warning turns on -Wnarrowing and is enabled by -Wall.
-Wc++14-compat (C++ and Objective-C++ only)
Warn about C++ constructs whose meaning differs between ISO C++ 2011 and ISO C++ 2014. This warning is enabled by -Wall.
Warn whenever a pointer is cast so as to remove a type qualifier from the target type. For example, warn if a const char * is cast to an ordinary char *.Also warn when making a cast that introduces a type qualifier in an unsafe way. For example, casting char ** to const char ** is unsafe, as in this example:

            /* p is char ** value.  */
            const char **q = (const char **) p;
            /* Assignment of readonly string to const char * is OK.  */
            *q = "string";
            /* Now char** pointer points to read-only memory.  */
            **p = 'b';
Warn whenever a pointer is cast such that the required alignment of the target is increased. For example, warn if a char * is cast to an int * on machines where integers can only be accessed at two- or four-byte boundaries.
When compiling C, give string constants the type const char[length] so that copying the address of one into a non-const char * pointer produces a warning. These warnings help you find at compile time code that can try to write into a string constant, but only if you have been very careful about using const in declarations and prototypes. Otherwise, it is just a nuisance. This is why we did not make -Wall request these warnings.When compiling C++, warn about the deprecated conversion from string literals to char *. This warning is enabled by default for C++ programs.

Warn for variables that might be changed by longjmp or vfork. This warning is also enabled by -Wextra.
-Wconditionally-supported (C++ and Objective-C++ only)
Warn for conditionally-supported (C++11 [intro.defs]) constructs.
Warn for implicit conversions that may alter a value. This includes conversions between real and integer, like abs (x) when x is double; conversions between signed and unsigned, like unsigned ui = -1; and conversions to smaller types, like sqrtf (M_PI). Do not warn for explicit casts like abs ((int) x) and ui = (unsigned) -1, or if the value is not changed by the conversion like in abs (2.0). Warnings about conversions between signed and unsigned integers can be disabled by using -Wno-sign-conversion.For C++, also warn for confusing overload resolution for user-defined conversions; and conversions that never use a type conversion operator: conversions to void, the same type, a base class or a reference to them. Warnings about conversions between signed and unsigned integers are disabled by default in C++ unless -Wsign-conversion is explicitly enabled.

-Wno-conversion-null (C++ and Objective-C++ only)
Do not warn for conversions between NULL and non-pointer types. -Wconversion-null is enabled by default.
-Wzero-as-null-pointer-constant (C++ and Objective-C++ only)
Warn when a literal ‘0’ is used as null pointer constant. This can be useful to facilitate the conversion to nullptr in C++11.
-Wsubobject-linkage (C++ and Objective-C++ only)
Warn if a class type has a base or a field whose type uses the anonymous namespace or depends on a type with no linkage. If a type A depends on a type B with no or internal linkage, defining it in multiple translation units would be an ODR violation because the meaning of B is different in each translation unit. If A only appears in a single translation unit, the best way to silence the warning is to give it internal linkage by putting it in an anonymous namespace as well. The compiler doesn’t give this warning for types defined in the main .C file, as those are unlikely to have multiple definitions. -Wsubobject-linkage is enabled by default.
Warn when macros __TIME__, __DATE__ or __TIMESTAMP__ are encountered as they might prevent bit-wise-identical reproducible compilations.
-Wdelete-incomplete (C++ and Objective-C++ only)
Warn when deleting a pointer to incomplete type, which may cause undefined behavior at runtime. This warning is enabled by default.
-Wuseless-cast (C++ and Objective-C++ only)
Warn when an expression is casted to its own type.
Warn if an empty body occurs in an if, else or do while statement. This warning is also enabled by -Wextra.
Warn about a comparison between values of different enumerated types. In C++ enumeral mismatches in conditional expressions are also diagnosed and the warning is enabled by default. In C this warning is enabled by -Wall.
-Wjump-misses-init (C, Objective-C only)
Warn if a goto statement or a switch statement jumps forward across the initialization of a variable, or jumps backward to a label after the variable has been initialized. This only warns about variables that are initialized when they are declared. This warning is only supported for C and Objective-C; in C++ this sort of branch is an error in any case.-Wjump-misses-init is included in -Wc++-compat. It can be disabled with the -Wno-jump-misses-init option.

Warn when a comparison between signed and unsigned values could produce an incorrect result when the signed value is converted to unsigned. This warning is also enabled by -Wextra; to get the other warnings of -Wextra without this warning, use -Wextra -Wno-sign-compare.
Warn for implicit conversions that may change the sign of an integer value, like assigning a signed integer expression to an unsigned integer variable. An explicit cast silences the warning. In C, this option is enabled also by -Wconversion.
Warn for implicit conversions that reduce the precision of a real value. This includes conversions from real to integer, and from higher precision real to lower precision real values. This option is also enabled by -Wconversion.
Do not warn on suspicious constructs involving reverse scalar storage order.
-Wsized-deallocation (C++ and Objective-C++ only)
Warn about a definition of an unsized deallocation function

          void operator delete (void *) noexcept;
          void operator delete[] (void *) noexcept;

without a definition of the corresponding sized deallocation function

          void operator delete (void *, std::size_t) noexcept;
          void operator delete[] (void *, std::size_t) noexcept;

or vice versa. Enabled by -Wextra along with -fsized-deallocation.

Warn for suspicious length parameters to certain string and memory built-in functions if the argument uses sizeof. This warning warns e.g. about memset (ptr, 0, sizeof (ptr)); if ptr is not an array, but a pointer, and suggests a possible fix, or about memcpy (&foo, ptr, sizeof (&foo));. This warning is enabled by -Wall.
Warn when the sizeof operator is applied to a parameter that is declared as an array in a function definition. This warning is enabled by default for C and C++ programs.
Warn for suspicious calls to the memset built-in function, if the second argument is not zero and the third argument is zero. This warns e.g. about memset (buf, sizeof buf, 0)where most probably memset (buf, 0, sizeof buf) was meant instead. The diagnostics is only emitted if the third argument is literal zero. If it is some expression that is folded to zero, a cast of zero to some type, etc., it is far less likely that the user has mistakenly exchanged the arguments and no warning is emitted. This warning is enabled by -Wall.
Warn about suspicious uses of memory addresses. These include using the address of a function in a conditional expression, such as void func(void); if (func), and comparisons against the memory address of a string literal, such as if (x == "abc"). Such uses typically indicate a programmer error: the address of a function always evaluates to true, so their use in a conditional usually indicate that the programmer forgot the parentheses in a function call; and comparisons against string literals result in unspecified behavior and are not portable in C, so they usually indicate that the programmer intended to use strcmp. This warning is enabled by -Wall.
Warn about suspicious uses of logical operators in expressions. This includes using logical operators in contexts where a bit-wise operator is likely to be expected. Also warns when the operands of a logical operator are the same:

          extern int a;
          if (a < 0 && a < 0) { ... }
Warn about logical not used on the left hand side operand of a comparison. This option does not warn if the RHS operand is of a boolean type. Its purpose is to detect suspicious code like the following:

          int a;
          if (!a > 1) { ... }

It is possible to suppress the warning by wrapping the LHS into parentheses:

          if ((!a) > 1) { ... }

This warning is enabled by -Wall.

Warn if any functions that return structures or unions are defined or called. (In languages where you can return an array, this also elicits a warning.)
Warn if in a loop with constant number of iterations the compiler detects undefined behavior in some statement during one or more of the iterations.
Do not warn if an unexpected __attribute__ is used, such as unrecognized attributes, function attributes applied to variables, etc. This does not stop errors for incorrect use of supported attributes.
Do not warn if certain built-in macros are redefined. This suppresses warnings for redefinition of __TIMESTAMP__, __TIME__, __DATE__, __FILE__, and __BASE_FILE__.
-Wstrict-prototypes (C and Objective-C only)
Warn if a function is declared or defined without specifying the argument types. (An old-style function definition is permitted without a warning if preceded by a declaration that specifies the argument types.)
-Wold-style-declaration (C and Objective-C only)
Warn for obsolescent usages, according to the C Standard, in a declaration. For example, warn if storage-class specifiers like static are not the first things in a declaration. This warning is also enabled by -Wextra.
-Wold-style-definition (C and Objective-C only)
Warn if an old-style function definition is used. A warning is given even if there is a previous prototype.
-Wmissing-parameter-type (C and Objective-C only)
A function parameter is declared without a type specifier in K&R-style functions:

          void foo(bar) { }

This warning is also enabled by -Wextra.

-Wmissing-prototypes (C and Objective-C only)
Warn if a global function is defined without a previous prototype declaration. This warning is issued even if the definition itself provides a prototype. Use this option to detect global functions that do not have a matching prototype declaration in a header file. This option is not valid for C++ because all function declarations provide prototypes and a non-matching declaration declares an overload rather than conflict with an earlier declaration. Use -Wmissing-declarations to detect missing declarations in C++.
Warn if a global function is defined without a previous declaration. Do so even if the definition itself provides a prototype. Use this option to detect global functions that are not declared in header files. In C, no warnings are issued for functions with previous non-prototype declarations; use -Wmissing-prototypes to detect missing prototypes. In C++, no warnings are issued for function templates, or for inline functions, or for functions in anonymous namespaces.
Warn if a structure’s initializer has some fields missing. For example, the following code causes such a warning, because x.h is implicitly zero:

          struct s { int f, g, h; };
          struct s x = { 3, 4 };

This option does not warn about designated initializers, so the following modification does not trigger a warning:

          struct s { int f, g, h; };
          struct s x = { .f = 3, .g = 4 };

In C++ this option does not warn either about the empty { } initializer, for example:

          struct s { int f, g, h; };
          s x = { };

This warning is included in -Wextra. To get other -Wextra warnings without this one, use -Wextra -Wno-missing-field-initializers.

Do not warn if a multicharacter constant (‘‘FOOF’’) is used. Usually they indicate a typo in the user’s code, as they have implementation-defined values, and should not be used in portable code.
In ISO C and ISO C++, two identifiers are different if they are different sequences of characters. However, sometimes when characters outside the basic ASCII character set are used, you can have two different character sequences that look the same. To avoid confusion, the ISO 10646 standard sets out some normalization rules which when applied ensure that two sequences that look the same are turned into the same sequence. GCC can warn you if you are using identifiers that have not been normalized; this option controls that warning.There are four levels of warning supported by GCC. The default is -Wnormalized=nfc, which warns about any identifier that is not in the ISO 10646 “C” normalized form, NFC. NFC is the recommended form for most uses. It is equivalent to -Wnormalized.

Unfortunately, there are some characters allowed in identifiers by ISO C and ISO C++ that, when turned into NFC, are not allowed in identifiers. That is, there’s no way to use these symbols in portable ISO C or C++ and have all your identifiers in NFC. -Wnormalized=id suppresses the warning for these characters. It is hoped that future versions of the standards involved will correct this, which is why this option is not the default.

You can switch the warning off for all characters by writing -Wnormalized=none or -Wno-normalized. You should only do this if you are using some other normalization scheme (like “D”), because otherwise you can easily create bugs that are literally impossible to see.

Some characters in ISO 10646 have distinct meanings but look identical in some fonts or display methodologies, especially once formatting has been applied. For instance \u207F, “SUPERSCRIPT LATIN SMALL LETTER N”, displays just like a regular n that has been placed in a superscript. ISO 10646 defines the NFKC normalization scheme to convert all these into a standard form as well, and GCC warns if your code is not in NFKC if you use -Wnormalized=nfkc. This warning is comparable to warning about every identifier that contains the letter O because it might be confused with the digit 0, and so is not the default, but may be useful as a local coding convention if the programming environment cannot be fixed to display these characters distinctly.

Do not warn about usage of deprecated features. See Deprecated Features.
Do not warn about uses of functions (see Function Attributes), variables (see Variable Attributes), and types (see Type Attributes) marked as deprecated by using the deprecatedattribute.
Do not warn about compile-time overflow in constant expressions.
Warn about One Definition Rule violations during link-time optimization. Requires -flto-odr-type-merging to be enabled. Enabled by default.
Warn if the vectorizer cost model overrides the OpenMP or the Cilk Plus simd directive set by user. The -fsimd-cost-model=unlimited option can be used to relax the cost model.
-Woverride-init (C and Objective-C only)
Warn if an initialized field without side effects is overridden when using designated initializers (see Designated Initializers).This warning is included in -Wextra. To get other -Wextra warnings without this one, use -Wextra -Wno-override-init.

-Woverride-init-side-effects (C and Objective-C only)
Warn if an initialized field with side effects is overridden when using designated initializers (see Designated Initializers). This warning is enabled by default.
Warn if a structure is given the packed attribute, but the packed attribute has no effect on the layout or size of the structure. Such structures may be mis-aligned for little benefit. For instance, in this code, the variable f.x in struct bar is misaligned even though struct bar does not itself have the packed attribute:

          struct foo {
            int x;
            char a, b, c, d;
          } __attribute__((packed));
          struct bar {
            char z;
            struct foo f;
The 4.1, 4.2 and 4.3 series of GCC ignore the packed attribute on bit-fields of type char. This has been fixed in GCC 4.4 but the change can lead to differences in the structure layout. GCC informs you when the offset of such a field has changed in GCC 4.4. For example there is no longer a 4-bit padding between field a and b in this structure:

          struct foo
            char a:4;
            char b:8;
          } __attribute__ ((packed));

This warning is enabled by default. Use -Wno-packed-bitfield-compat to disable this warning.

Warn if padding is included in a structure, either to align an element of the structure or to align the whole structure. Sometimes when this happens it is possible to rearrange the fields of the structure to reduce the padding and so make the structure smaller.
Warn if anything is declared more than once in the same scope, even in cases where multiple declaration is valid and changes nothing.
-Wnested-externs (C and Objective-C only)
Warn if an extern declaration is encountered within a function.
Suppress warnings about use of C++11 inheriting constructors when the base class inherited from has a C variadic constructor; the warning is on by default because the ellipsis is not inherited.
Warn if a function that is declared as inline cannot be inlined. Even with this option, the compiler does not warn about failures to inline functions declared in system headers.The compiler uses a variety of heuristics to determine whether or not to inline a function. For example, the compiler takes into account the size of the function being inlined and the amount of inlining that has already been done in the current function. Therefore, seemingly insignificant changes in the source program can cause the warnings produced by -Winlineto appear or disappear.

-Wno-invalid-offsetof (C++ and Objective-C++ only)
Suppress warnings from applying the offsetof macro to a non-POD type. According to the 2014 ISO C++ standard, applying offsetof to a non-standard-layout type is undefined. In existing C++ implementations, however, offsetof typically gives meaningful results. This flag is for users who are aware that they are writing nonportable code and who have deliberately chosen to ignore the warning about it.The restrictions on offsetof may be relaxed in a future version of the C++ standard.

Suppress warnings from casts to pointer type of an integer of a different size. In C++, casting to a pointer type of smaller size is an error. Wint-to-pointer-cast is enabled by default.
-Wno-pointer-to-int-cast (C and Objective-C only)
Suppress warnings from casts from a pointer to an integer type of a different size.
Warn if a precompiled header (see Precompiled Headers) is found in the search path but can’t be used.
Warn if long long type is used. This is enabled by either -Wpedantic or -Wtraditional in ISO C90 and C++98 modes. To inhibit the warning messages, use -Wno-long-long.
Warn if variadic macros are used in ISO C90 mode, or if the GNU alternate syntax is used in ISO C99 mode. This is enabled by either -Wpedantic or -Wtraditional. To inhibit the warning messages, use -Wno-variadic-macros.
Warn upon questionable usage of the macros used to handle variable arguments like va_start. This is default. To inhibit the warning messages, use -Wno-varargs.
Warn if vector operation is not implemented via SIMD capabilities of the architecture. Mainly useful for the performance tuning. Vector operation can be implemented piecewise, which means that the scalar operation is performed on every vector element; in parallel, which means that the vector operation is implemented using scalars of wider type, which normally is more performance efficient; and as a single scalar, which means that vector fits into a scalar type.
Suppress warnings about inheriting from a virtual base with a non-trivial C++11 move assignment operator. This is dangerous because if the virtual base is reachable along more than one path, it is moved multiple times, which can mean both objects end up in the moved-from state. If the move assignment operator is written to avoid moving from a moved-from object, this warning can be disabled.
Warn if variable length array is used in the code. -Wno-vla prevents the -Wpedantic warning of the variable length array.
Warn if a register variable is declared volatile. The volatile modifier does not inhibit all optimizations that may eliminate reads and/or writes to register variables. This warning is enabled by -Wall.
Warn if a requested optimization pass is disabled. This warning does not generally indicate that there is anything wrong with your code; it merely indicates that GCC’s optimizers are unable to handle the code effectively. Often, the problem is that your code is too big or too complex; GCC refuses to optimize programs when the optimization itself is likely to take inordinate amounts of time.
-Wpointer-sign (C and Objective-C only)
Warn for pointer argument passing or assignment with different signedness. This option is only supported for C and Objective-C. It is implied by -Wall and by -Wpedantic, which can be disabled with -Wno-pointer-sign.
This option is only active when -fstack-protector is active. It warns about functions that are not protected against stack smashing.
Warn about string constants that are longer than the “minimum maximum” length specified in the C standard. Modern compilers generally allow string constants that are much longer than the standard’s minimum limit, but very portable programs should avoid using longer strings.The limit applies after string constant concatenation, and does not count the trailing NUL. In C90, the limit was 509 characters; in C99, it was raised to 4095. C++98 does not specify a normative minimum maximum, so we do not diagnose overlength strings in C++.

This option is implied by -Wpedantic, and can be disabled with -Wno-overlength-strings.

-Wunsuffixed-float-constants (C and Objective-C only)
Issue a warning for any floating constant that does not have a suffix. When used together with -Wsystem-headers it warns about such constants in system header files. This can be useful when preparing code to use with the FLOAT_CONST_DECIMAL64 pragma from the decimal floating-point extension to C99.
-Wno-designated-init (C and Objective-C only)
Suppress warnings when a positional initializer is used to initialize a structure that has been marked with the designated_init attribute.

AngularJS vs. Backbone.js vs. Ember.js

1 Introduction

In this article we are going to compare three popular MV* frameworks for the web: AngularJS vs. Backbone vs. Ember. Choosing the right framework for your project can have a huge impact on your ability to deliver on time, and your ability to maintain your code in the future. You probably want a solid, stable and proven framework to build upon, but don’t want to be limited by your choice. The web is evolving fast — new technologies arise, and old methodologies quickly become irrelevant. Under this light, we are going to go through an in-depth comparison of the three frameworks.

2 Meet The Frameworks

All the frameworks we are going to meet today have a lot in common: they are open-sourced, released under the permissive MIT license, and try to solve the problem of creating Single Page Web Applications using the MV* design pattern. They all have the concept of views, events, data models and routing. We are going to start with some quick background and history, and then dive in to compare the three frameworks.

AngularJS was born in 2009 as a part of a larger commercial product, called GetAngular. Shortly after, Misko Hevery, one of the engineers who founded GetAngular, managed to recreate a web application that consisted of 17 thousand lines of code and took 6 months to develop in a mere 3 weeks using just GetAngular. Reducing the size of the application to just about 1,000 lines of code convinced Google to start sponsoring the project, turning it into the open-source AngularJS we know today. Amongst Angular’s unique and innovative features are two-way data bindings, dependency injection, easy-to-test code and extending the HTML dialect by using directives.

Backbone.js is a lightweight MVC framework. Born in 2010, it quickly grew popular as a lean alternative to heavy, full-featured MVC frameworks such as ExtJS. This resulted in many services adopting it, including Pinterest, Flixster, AirBNB and others.

Ember’s roots go way back to 2007. Starting its life as the SproutCore MVC framework, originally developed by SproutIt and later by Apple, it was forked in 2011 by Yehuda Katz, a core contributor to the popular jQuery and Ruby on Rails projects. Notable Ember users include Yahoo!, Groupon, and ZenDesk.

3 Community

Community is one of the most important factors to consider when choosing a framework. A large community means more questions answered, more third-party modules, more YouTube tutorials…you get the point. I have put together a table with the numbers, as of June 30, 2015. Angular is definitely the winner here, being the 3rd most-starred project on GitHub and having more questions on StackOverflow than Ember and Backbone combined, as you can see below:


Metric AngularJS Backbone.js Ember.js
Stars on Github 40.2k 18.8k 14.1k
Third-Party Modules 1488 ngmodules 256 backplugs 1155 emberaddons
StackOverflow Questions 104k 18.2k 15.7k
YouTube Results ~93k ~10.6k ~9.1k
GitHub Contributors 96 265 501
Chrome Extension Users 275k 15.6k 66k
Open Issues 922 13 413
Closed Issues 5,520 2,062 3,350

All those metrics, however, merely show the current state of each framework. It is also interesting to see which framework has a faster-growing popularity. Fortunately, using Google Trends we can get an answer for that too:

4 Framework Size

Page load times are crucial for the success of your web site. Users do not exhibit much patience when it comes to the speed of browsing — so in many cases it is desired to do everything possible to make your application load as fast as possible. There are two factors to look at when considering the impact of the framework on the loading time of your application: framework size and the time it takes the framework to bootstrap.

Javascript assets are usually served minified and gzipped, so we are going to compare the size of the minified-gzipped versions. However, merely looking at the framework is not enough. Backbone.js, despite being the smallest (only 6.5kb), requires both Underscore.js (5kb) and jQuery (32kb) or Zepto (9.1kb), and you will probably need to add some third party plug-ins to the mix.

Framework Net Size Size with required dependencies
AngularJS 1.2.22 39.5kb 39.5kb
Backbone.js 1.1.2 6.5kb 43.5kb (jQuery + Underscore)
20.6kb (Zepto + Underscore)
Ember.js 1.6.1 90kb 136.2kb (jQuery + Handlebars)

5 Templating

Angular and Ember include a template engine. Backbone, on the other hand, leaves it up to you to use the template engine of your choice. The best way to get a feeling of the different templating engines is a code sample, so let’s dive in. We will show an example of formatting a list of items as HTML.

5.1 AngularJS

Angular’s Templating engine is simply HTML with binding expressions baked-in. Binding expressions are surrounded by double curly braces:

    <li ng-repeat="framework in frameworks" title="{{framework.description}}">               

5.2 Backbone.js

While Backbone can be integrated with many third-party template engines, the default choice is Underscore templates. Since Underscore is a Backbone dependency and you already have it on your page, you can easily take advantage of its templating engine without adding any additional dependencies for your application. On the downside, the templating engine of Underscore is very basic and you usually have to throw javascript into the mix, as you can see in our example:

    <% _.each(frameworks, function(framework) { %> 
        <li title="<%- framework.description %>"> 
            <%- %> 
    <% }); %> 

5.3 Ember.js

Ember currently uses the Handlebars template engine, which is an extension to thepopular Mustache templating engine. A new Handlebars variant, called HTMLBars is currently in the works. Handlebars does not understand DOM – all it does is a simple string transformation. HTMLBars will understand DOM, so the variable interpolation will be context aware. As HTMLBars is still not production-ready, we will show the Handlebars way of printing the framework list:

    {{#each frameworks}} 
        <li {{bind-attr title=description}}> 

6 AngularJS

6.1 The Good Parts

Angular has brought many innovative concepts to the world of web developers. Two-way data binding saves a lot of boilerplate code. Consider the following jQuery code snippet:

$('#greet-form input.user-name').on('value', function() { 
    $('#greet-form div.user-name').text('Hello ' + this.val() + '!'); 

Thanks to Angular’s two-way-binding, you never have to write this code yourself. Rather, you just declare the bindings in your HTML template:

<input ng-model="" type="text" />
Hello {{}}!

Promises play a main role in the Angular cast. Javascript is a single-thread, event-loop based language, which implies that many operations (such as network communication) happen in an asynchronous manner. Asynchronous javascript code tends to grow quickly into a spaghetti of nested callbacks, better recognized as “Pyramid Code” or “Callback Hell.”

Not only does Angular have the largest community and much more online content than the two others, it is also backed and promoted by Google. As such, the core team is constantly growing, resulting in innovation and tools that improve developer productivity: Protractor, Batarang, ngmin and Zone.js, just to name a few. In addition, the team collaborates with the community on the design decisions. For example, all the design documents for Angular 2.0 can be found here, and everyone can make suggestions directly to the design documents.

Angular helps you categorize your application building blocks into several types: Controllers, Directives, Factories, Filters, Services and Views (templates). Those are organized in turn into modules, which can depend one upon the other. Each type of building block has a different role. Views do the UI, Controllers work out the logic behind the UI, Services take care of communication with the backend and hold together pieces of common and related functionality, while Directives make it easy to create reusable components and extending HTML by defining new elements, attributes and behaviors.

The automatic Dirty Checking means that you don’t have to access your model data with getters and setters — you can modify any property of an arbitrary scope object and angular will automatically detect the change and notify all the watchers for that property.

“Angular is written with testability in mind.” This quote from the unit-testing guide has a lot behind it – Angular indeed puts a lot of emphasis on separation of concerns, unit isolation and provides ready-to-use, powerful mocks for fundamental built-in services such as $http and $timeout.

6.2 Pain Points

Angular is often criticized for the complexity of the Directives API. Transclusion, in particular, is a concept which confuses many developers and wrapping your head around all the concepts such as compiling function, pre/post linking functions, the different scope kinds (transclusion/isolate/child scope) and all the other configuration settings for directives takes some time to master.

The scope hierarchy in Angular uses Prototypal Inheritance, which is a new concept to grasp for people coming from Object Oriented languages such as Java and C#. Failing to understand scope inheritance causes many cases of frustrated developers (examples: here, here and here).

Angular Expressions are used extensively in the View layer of Angular. This expression language is very powerful, sometimes too powerful. It lets the developer use complicated logic and even perform assignment operations and calculations, all inside the view templates. Putting logic inside the templates makes it harder to test, as it becomes impossible to test it in isolation. Consider the following code example, which clearly shows how easily the template language can be abused:

<button ng-click="(oldPassword && checkComplexity(newPassword) && oldPassword != newPassword) ? (changePassword(oldPassword, newPassword) && (oldPassword=(newPassword=''))) : (errorMessage='Please input a new password matching the following requirements: ' + passwordRequirements)">Click me</button>

In many cases, mistakes such as misspelling a directive name or calling an undefined scope function are silently ignored and can be challenging to find, especially when you throw into the mix the complexity of the directive API and the scope inheritance mentioned above. I have seen developers spending hours scratching their head trying to figure out why an event binding didn’t fire the callback function on the scope, only to find out they have used the camelCase convention instead of the hyphen-separated one when spelling attribute names (example here).

Finally, the Digest Cycle of angular, which takes care of the “Magical” dirty checking, has the tendency to surprise developers. It is easy to forget to call $digest() when running in non-Angular context (example). On the other hand, you have to be very careful not to cause slow watches or infinite digest loops (examples: here, here andhere). In general, for pages with a lot of interactive elements, Angular becomes really slow. A good rule of thumb is not to have more than 2,000 active bindings on the same page.

7 Backbone.js

7.1 The Good Parts

Backbone is lightweight, fast and has a small memory footprint. The learning curve is very linear, and there are only a few simple concepts to grasp (Models/Collections, Views, Routes). It has great documentation, the code is simple and heavily documented, and there is even an annotated version of the code which explains how it works in detail. You can actually go over the entire source code of the framework and get familiar with it in less than an hour.

Being so small and basic, Backbone can be a good foundation to build your own framework upon. Some examples of 3rd party frameworks based on Backbone are Aura, Backbone UI, Chaplin, Geppetto, Marionette, LayoutManager, Thorax, Vertebrae. With Angular and Ember you usually have to live with the choices made by the authors of the frameworks, which may or may not suit your project needs and personal style. Angular 2.0 promises to change it, by comprising small independent modules, so you will be able to pick and mix. We are yet to see if they will be able to deliver this.

7.2 Pain Points

Backbone does not provide structure. It rather provides some basic tools you can use to create structure, leaving it up to the developer to decide how to structure his application, and there are also many blanks to fill. Things such as memory management have to be carefully considered. The lack of view lifecycle management makes route/state changes prone to memory leaks unless you take care of cleaning up everything yourself.

While it is true that many of the functions not provided by Backbone itself could be filled by third-party plugins, this also means that there are many choices to be made when creating an application, as many functions have several alternative plugins. For example, nested models can be provided by Backbone.DocumentModel, BackBone.NestedTypes, Backbone.Schema, Backbone-Nested, backbone-nestify, just to name a few. Deciding which one is the best for your project requires research, which in turn takes time — and one of the main purposes of framework is to save you time.

Backbone lacks support for two-way data binding, meaning you will have to write a lot of boilerplate to update the view whenever your model changes, and to update your model whenever the view changes. See the example given above, showing how two-way in Angular.js data binding reduces boilerplate.

Views in Backbone manipulate the DOM directly, making them really hard to unit-test, more fragile and less reusable. The common practice is to look up DOM elements using CSS selectors, so changing a CSS class name, adding a new element with the same class name or even wrapping some DOM tree inside another element can break your CSS selectors and render your app unusable.

8 Ember.js

8.1 The Good Parts

Ember.js favors Convention over Configuration. This means that instead of writing a lot of boilerplate code, Ember can automatically infer much of the configuration itself, such as automatically determining the name of the route and the controller when defining a router resource. Ember even raises the bar by automatically creating the controller for your resource if you don’t define one yourself.

Ember includes both an excellent router and an optional data layer, called ember data. Unlike the two other frameworks, which have a very minimal data layer (Backbone’s Collection/Model and Angular’s $resource), Ember comes out of the box with a fully-fledged data module which integrates really nicely with a Ruby-on-Rails backend or any other RESTful JSON API that follows a simple set of conventions. It also provides support for setting up fixtures for developing against mock API and testing.

Performance has been a major goal in the design of Ember.js. Concepts such as The Run Loop, which ensures that updated data only causes a single DOM update even if the same piece of data was updated several times, along with caching of computed properties, and the ability to precompile the HandleBars templates during the build time or on your server, help to keep your application load and run fast.

8.2 Pain Points

Ember’s API changed much before it stabilized. Therefore, there is a lot of outdated content and examples that no longer work, making it confusing for developers who are making their first steps in the framework. Take a look at the Ember Data Changelog, and you will see what I mean. There are so many breaking changes, and those cause many StackOverflow answers and coding tutorials to become irrelevant (example here).

Handlebars pollutes the DOM with many <script> tags which it uses as markers tokeep the templates up to date with your model. This will be gone with the transition to HTMLBars, but for the time being, your DOM tree will be filled up with so many<script> tags you will barely be able to recognize your own code. And the worst part – this can also break your CSS styling or integration with other frameworks, such as jQuery UI’s Sortable.

9 Summary

We have seen the strengths and weaknesses of all the three frameworks. Ember’s holistic approach which embraces MVC structure will make a lot of sense for developers who have a MVC programming background in Ruby, Python, Java, C# or any other Object Oriented language. Ember also brings application performance to the table, and excels at saving you from writing boilerplate by favoring convention over configuration.

Backbone embraces minimalism. It is small, fast and easy to learn, and provides the minimum (or in many cases, even less than the minimum) that you need to get going.

Angular’s innovative approach for extending HTML will make a lot of sense for people who are web developers in soul. With a large community and Google behind it, it is here to stay and grow, and it works well both for quick prototyping projects and large-scale production applications.

Original Reference: Click Here

Thanks, and Keep Coding

Mishra Vinay

Solution’s Point

iDev: Guidelines for installing custom enterprise apps on iOS

Guidelines for installing custom enterprise apps on iOS

Follow these security guidelines to install custom apps created for your organization.

Organizations can use the Apple Developer Enterprise Program to create proprietary enterprise apps for iOS devices and to distribute them to employees for internal use. Before one of these apps can be opened, it must be trusted.
Trust is established automatically if the app is installed by Mobile Device Management (MDM). If you install an app manually you must also manually establish trust as described below.

Apple recommends using an (MDM) solution to distribute the apps because it is secure and requires no user interaction. Users can also install these custom apps from a secure website operated by their organization. If you’re not installing an app from your organization, the best way to protect your iPhone, iPad, or iPod touch is to download and install apps only from the Apple App Store.

Manually Installing and Trusting an Enterprise App

When you first open an enterprise app you’ve manually installed, you see a notification that the developer of the app isn’t trusted on your device. You can dismiss this message but you can’t open the app.

After dismissing this message you can establish trust for this app developer. Tap Settings > General > Profiles or Profiles & Device Management. You then see a a profile for the developer under the “Enterprise App” heading.


Tap the profile to establish trust for this developer.


You’re then prompted to confirm your choice. Once you trust this profile, you can manually install other apps from the same developer and open them immediately. This developer remains trusted until you use the Delete App button to remove all apps from the developer.


An Internet connection is required to verify the app developer’s certificate when establishing trust. If you’re behind a firewall, make sure it’s configured to allow connections to If you aren’t connected to the Internet when you trust an app, the device displays “Not Verified” instead. In order to use the app, you need to connect to the Internet, and tap the Verify App button.

Original Source:

iDev: Apple ResearchKit Turns iPhones Into Medical Diagnostic Devices

iDev: Apple ResearchKit Turns iPhones Into Medical Diagnostic Devices by

Medical research is plagued by small sample sizes and inconsistent data collection. So Apple is stepping up to help health innovation with Research Kit, a new iOS software framework that lets people volunteer to join medical research studies. ResearchKit lets people take tests like saying “ahhh” to detect vocal variations, walking in a line, or tapping in rhythm to test for Parkinson’s Disease.

Users will decide how to share their data and Apple won’t see it. And to advance its evolution, ResearchKit will be open source. ResearchKit will be available next month, and the first five tests built with it will become available today. They help people participate in tests for Parkinson’s, diabetes, cardiovascular disease, asthma, and breast cancer.

Tap Test

Apple’s Jeff Williams came out on stage today at the Apple Watch event to show off ResearchKit. He explained how Apple worked with 12 research institutions to build out the app, including University Of Oxford and Stanford.

Apple learned about some of the biggest obstacles to scientific research in medicine. Finding and recruiting subjects can be tough. Paper flyers on college campuses are one of the few ways labs sign up human guinea pigs. This obstacle can lead to small sample sizes more vulnerable to inaccuracy, and less diverse samples that might not be generalizable to the world population.

Screen Shot 2015-03-09 at 10.39.04 AM

5 ResearchKit Apps

With ResearchKit, researchers can build out a medical testing app for iOS that’s accessible to people far from their physical lab. Users can signup with a digital signature, and instantly start recording data.

Screen Shot 2015-03-09 at 10.56.38 AM

Tests designed with ResearchKit use the iPhone’s sensors to record data. The touch screen can feel people tapping in rhythm to detect inconsistencies that may signal a disease. The accelerometer can compare the gait and balance of someone’s walk against a healthy person’s speed and posture. And the microphone can notice minute fluctuations in someone’s voice that may indicate Parkinson’s or another health problem.

Gait Test

Williams stressed the immediate benefit to users because they’re learn about their health even before a researcher’s study concludes and they publish the results. If a user notices they are having trouble balancing while walking a line, they can talk to their doctor about it.

Since medical data is obviously sensitive, Apple won’t see anything you put into ResearchKit apps and you can give permissions for how data is used by researchers.

The question will be how many developers jump aboard the ResearchKit. While it obviously holds potential improvements, it also takes time to develop traditional lab studies into an app. ResearchKit is a valiant effort by Apple, and if its a hit with scientists, it could make mass medical research easier than ever.

Original Blog Source : Click Here

iDev: Learn Swift Tutorial Series

Hi Friends,

Hope you all doing good!!!

Now I am start posting to Learning the Swift Language (Apple introduce WWDC 2014). In every tutorial I put example to learn better and best practice way to do the coding.

My first post on Swift will be coming soon on August, In which I explain the basic of Swift and some sample code to understand the structure of Swift language.

Here a snaps of swift :


var colors = [“red”, “blue”]
var moreColors: String[] = [“orange”, “purple”] // explicit type
colors.append(“green”) // [red, blue, green]
colors += “yellow” // [red, blue, green, yellow]
colors += moreColors // [red, blue, green, yellow, orange, purple]

var days = [“mon”, “thu”]
var firstDay = days[0] // mon
days.insert(“tue”, atIndex: 1) // [mon, tue, thu]
days[2] = “wed” // [mon, tue, wed]
days.removeAtIndex(0) // [tue, wed]


class Counter {
var count: Int = 0
func inc() {
func add(n: Int) {
count += n
func printCount() {
println(“Count: \(count)”)

var myCount = Counter()
myCount.printCount() // Count: 3


let happy = true
if happy {
println(“We’re Happy!”)
} else {
println(“We’re Sad :(‘”)
// We’re Happy!

let speed = 28
if speed <= 0 {
} else if speed <= 30 {
println(“Safe speed”)
} else {
println(“Too fast!”)
// Safe speed

let n = 2
switch n {
case 1:
println(“It’s 1!”)
case 2…4:
println(“It’s between 2 and 4!”)
case 5, 6:
println(“It’s 5 or 6”)
println(“Its another number!”)
// It’s between 2 and 4!


let myInt = 1
myInt = 2 // compile-time error!


var days = [“mon”: “monday”, “tue”: “tuseday”]
days[“tue”] = “tuesday” // change the value for key “tue”
days[“wed”] = “wednesday” // add a new key/value pair

var moreDays: Dictionary = [“thu”: “thursday”, “fri”: “friday”]
moreDays[“thu”] = nil // remove thu from the dictionary
moreDays.removeValueForKey(“fri”) // remove fri from the dictionary


enum CollisionType: Int {
case Player = 1
case Enemy = 2
var type = CollisionType.Player

For Loops

for var index = 1; index < 3; ++index {
// loops with index taking values 1,2
for index in 1..3 {
// loops with index taking values 1,2
for index in 1…3 {
// loops with index taking values 1,2,3

let colors = [“red”, “blue”, “yellow”]
for color in colors {
println(“Color: \(color)”)
// Color: red
// Color: blue
// Color: yellow

let days = [“mon”: “monday”, “tue”: “tuesday”]
for (shortDay, longDay) in days {
println(“\(shortDay) is short for \(longDay)”)
// mon is short for monday
// tue is short for tuesday


func iAdd(a: Int, b: Int) -> Int {
return a + b
iAdd(2, 3) // returns 5

func eitherSide(n: Int) -> (nMinusOne: Int, nPlusOne: Int) {
return (n-1, n+1)
eitherSide(5) // returns the tuple (4,6)

Logical Operators

var happy = true
var sad = !happy // logical NOT, sad = false
var everyoneHappy = happy && sad // logical AND, everyoneHappy = false
var someoneHappy = happy || sad // logical OR, someoneHappy = true


let name = “swift”
println(“My name is \(name)”)
print(“See you “)
My name is swift
See you later


var myString = “a”
let myImmutableString = “c”
myString += “b” // ab
myString = myString + myImmutableString // abc
myImmutableString += “d” // compile-time error!

let count = 7
let message = “There are \(count) days in a week”


var myInt = 1
var myExplicitInt: Int = 1 // explicit type
var x = 1, y = 2, z = 3 // declare multiple integers
myExplicitInt = 2 // set to another integer value

Source Ref: Press Here

Thanks Friends:)

Keep Coding:)

Mishra Vinay
Solution’s Point

iDev: Design Patterns

Creation Design Patterns in Cocoa Touch Framework

Christopher Alexander, a noted design architect, defined design pattern as:

Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice.

This blog lists some well-known examples for 5 Creational Design Patterns as applicable in Cocoa Touch Framework

Creational design patterns specifically target the problems of how an object is created and instantiated. These patterns were originally described in the Gang of Four (GoF) book on Design Patterns which is regarded as an important source for object-oriented design theory and practice. 

1. Abstract Factory 

The intent of Abstract Factory design pattern as specified in GoF is: 

Provide an interface for creating families of related or dependent objects without 

specifying their concrete classes.

We use Abstract Method pattern to create objects when we want to provide a class library of products, and we want to reveal just their interfaces, not their implementations. So the system is independent of how its products are created and represented.

The Abstract Factory pattern is commonly seen in the Cocoa Touch Framework and a lot of Foundation classes have used the pattern.

The interface declared by the abstract superclass, NSNumber in Foundation Framework serves a good example for this design pattern. 

 Consider these messages:

NSNumber *aChar = [NSNumber numberWithChar:’a’];

NSNumber *anInt = [NSNumber numberWithInt:1];

NSNumber *aFloat = [NSNumber numberWithFloat:1.0];

NSNumber *aDouble = [NSNumber numberWithDouble:1.0]; 

Each returned object — aChar, anInt, aFloat, and aDouble  share a common public interface which is the interface declared by the abstract superclass, NSNumber.

@interface NSNumber : NSValue

 – (char)charValue;

– (int)intValue;

– (float)floatValue;

– (double)doubleValue;



@interface NSNumber (NSNumberCreation)

+ (NSNumber *)numberWithChar:(char)value;

+ (NSNumber *)numberWithInt:(int)value;

+ (NSNumber *)numberWithFloat:(float)value;

+ (NSNumber *)numberWithDouble:(double)value;


but each object returned by the factory methods (numberWithChar, numberWithInt) belong to a different private subclass which is hidden to users. 

On a side note, NSNumber is also a “class cluster”. Class clusters are based on the Abstract Factory design pattern as discussed in “Cocoa Design Patterns.”

2. Factory Method

The intent of Factory Method design pattern as provided in GoF is:  

Define an interface for creating an object, but let subclasses decide which class 

to instantiate. 

We use the Factory Method pattern when a class wants its subclasses to specify the objects it creates. 

As an example, again consider NSNumber class in the Foundation framework which defines several class factory methods:

+ numberWithBool:

+ numberWithChar:

+ numberWithDouble:

+ numberWithFloat:

+ numberWithInt:

+ numberWithInteger:

+ numberWithLong:

+ numberWithLongLong:

+ numberWithShort:

+ numberWithUnsignedChar:

+ numberWithUnsignedInt:

+ numberWithUnsignedInteger:

+ numberWithUnsignedLong:

+ numberWithUnsignedLongLong:

+ numberWithUnsignedShort: 

These methods combine the two steps of allocating and initializing to return new, initialized instances of the class which are returned by the subclasses of the class where they are declared.

Having mentioned both Factory Method and Abstract Factory Method patterns, it is sometimes difficult to differentiate between the two. If we revisit the example for NSNumber class, in Factory Method pattern, we have a factory that creates objects that derive from a particular base class. So considering this example,

 NSNumber aNum = [NSNumber numberWithInt:1];

Here numberWithInt is the “factory” that allocates, initializes, and returns the “product object “ aNum

while in Abstract Factory pattern we have a factory that creates other factories, and these factories in turn create objects derived from base classes. In other word, in this example, the methods of the NSNumber Abstract Factory are implemented as Factory Methods. 

 3. Prototype

As per GoF, sometimes when instances of a class can have one of only a few different combinations of state it it is more convenient to have a corresponding number of prototypes and reuse them rather than creating the class each time with the appropriate state.

Under this scenario, it advises us to use Prototype Design Pattern. This applicability reminds us of the prototype cells we use in UITableView.

 As per Apple developer guide:

Use dynamic prototypes to design one cell and then use it as the template for other cells in the table. Use a dynamic prototype when multiple cells in a table should use the same layout to display information. 

Consider this example:



#define PHOTO_TAG 3

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @”ImageOnRightCell”; 

    UILabel *firstLabel, *secondLabel;

    UIImageView *photo;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

         if (cell == nil) {

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]];

        cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;

        firstLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 220.0, 15.0)]];

        firstLabel.tag = FIRST_LABEL_TAG;

        firstLabel.font = [UIFont systemFontOfSize:14.0];

        firstLabel.textAlignment = UITextAlignmentRight;

        firstLabel.textColor = [UIColor blackColor];

        [cell.contentView addSubview:firstLabel];


        secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 20.0, 220.0, 25.0)]];

        secondLabel.tag = SECOND_LABEL_TAG;

        secondLabel.font = [UIFont systemFontOfSize:12.0];

        secondLabel.textAlignment = UITextAlignmentRight;

        secondLabel.textColor = [UIColor darkGrayColor];

        [cell.contentView addSubview:secondLabel];

        photo = [[[UIImageView alloc] initWithFrame:CGRectMake(225.0, 0.0, 80.0, 45.0)]];

        photo.tag = PHOTO_TAG;

        photo.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;

        [cell.contentView addSubview:photo];

  } else {

        firstLabel = (UILabel *)[cell.contentView viewWithTag:FIRST_LABEL_TAG];

        secondLabel = (UILabel *)[cell.contentView viewWithTag:SECOND_LABEL_TAG];

        photo = (UIImageView *)[cell.contentView viewWithTag:PHOTO_TAG];


    NSDictionary *aDict = [self.list objectAtIndex:indexPath.row];

    firstLabel.text = [aDict objectForKey:@”mainTitleKey”];

    secondLabel.text = [aDict objectForKey:@”secondaryTitleKey”];

    NSString *imagePath = [[NSBundle mainBundle] pathForResource:[aDict objectForKey:@”imageKey”] ofType:@”png”];

    UIImage *theImage = [UIImage imageWithContentsOfFile:imagePath];

    photo.image = theImage;

    return cell;


Here we create a prototype for a cell in – tableView:cellForRowAtIndexPath: method as follows:

We create an instance of UITableViewCell and assign it a reuseIdentifier 

cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]];

 We then add subviews to it based on our design

 [cell.contentView addSubview:firstLabel];



[cell.contentView addSubview:secondLabel];



[cell.contentView addSubview:photo]; 

This prototype is now ready, and we use use this fully initialised cell as a prototype for other cells in our table view. 

 – tableView:cellForRowAtIndexPath: method first tries to acquire a cell by using dequeueReusableCellWithIdentifier.If a cell is not yet created, it creates it by using the prototype cell we had defined.

4. Singleton 

The intent of Singleton design pattern as provided in GoF is:  

Ensure a class only has one instance, and provide a global point of access to it. 

Regarding ‘Applicability’, the book states to use the Singleton pattern when

There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point

 Some common scenarios when we use Singletons in the Cocoa Touch Framework are

a. When an application is launched, the UIApplicationMain function (we can find it in main.m class in our project) is called and it creates a singleton UIApplication object. UIApplication class provides a centralized point of control for an iOS application. We can access this singleton object from any class in our project by invoking the sharedApplication class method:

 UIApplication *applicationSingleton = [UIApplication sharedApplication];

b. UIAccerometer’s sharedAccelerometer class method returns the the singleton shared accelerometer object for the system:

UIAccelerometer *accelerometerSingleton = [UIAccelerometer sharedAccelerometer];

5. Builder 

The intent of Builder design pattern as provided in GoF is:  

Separate the construction of a complex object from its representation so that 

the same construction process can create different representations. 

Unlike creational patterns that construct objects in one go, the Builder pattern constructs the object step by step. It is used in creation of a complex object. 

The builder pattern is not too much adopted in Objective-C as in java. Eric Buck, author ofCocoa Design Patterns, in one of his interview has said

“I think all of the famous GoF patterns exist within Cocoa, but many are either trivially implemented or made less necessary thanks to Objective-C. For example, the Cocoa convention of two stage allocation and initialization makes the GoF Abstract factory and Builder patterns trivial.”

In one flavor, as described in the book – Learn Objective-C for Java Developerscategories can be used for Builder Pattern in Objective C. The complex construction code is isolated from the main class definition via a category.


We saw how Cocoa Touch Framework uses different creational design patterns to create objects and their intent behind choosing a particular design pattern while creation of an object. For eg. Abstract Factory, Builder, and Prototype patterns – all 3 involve creating a new “factory object” which creates “product objects”.  But each differ the way the product objects are created – Abstract Factory factory object produces objects of several classes. Prototype has the factory object building a product by copying a prototype object while Builder has the factory object building a complex product incrementally. 

This blog listed only the design patterns used in the creation of objects. There are also structural and behavioral design patterns. It is always good to have a knowledge of wide variety of design patterns and the intent behind the use of a particular design pattern.

This helps us to leverage the knowledge of our industry experts and reuse it in our application design. Of course, the applicability of a particular design pattern depends on various factors. We must carefully choose from different design patterns. Understanding how the Cocoa Touch Framework uses these patterns, gives us a fair idea about their usage.

Source: Press Here

 Thanks 🙂

Solutions Point:)

Keep Coding 🙂


iDev: Copy a plist file to documents folder

Hi Friends,

Here a code snapshot for your help on Copy a plist file to Documents Folder

BOOL isSuccess;
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"idevCopyData.plist"];
isSuccess = [fileManager fileExistsAtPath:filePath];
if (isSuccess) return;
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingFormat:@"idevCopyData.plist"];
isSuccess = [fileManager copyItemAtPath:path toPath:filePath error:&error];
if (!isSuccess) {
NSAssert1(0, @"Failed to copy Plist. Error %@", [error localizedDescription]);


Reference : Here

Thanks 🙂


iDev: Change iOS project “My Mac 64-bit” to “iOS Device”

Hi Friends,

XCode iOS project only shows “My Mac 64-bit”!!!

The Simulator and Device options to Build/Run your have have disappeared.
This happened to  me after I changed the project name once or changed by another person.

solution #1:

  1. – Close Xcode.
  2. – Locate your Project folder.
  3. – Right-click on the AppName.xcodeproj file and click show package contents.
  4. – Now delete everything inside the xcuserdata folder.

If this does not work trying this:

  1. – open Xcode (obviously)
  2. – clicked on Manage Schemes and then Autocreate Schemes Now.
  3. – Then select the new scheme in Xcode.

Now you should get back all device/simulator options.

Thanks 🙂

Keep Coding 🙂

iDev: Objective-C Associated Objects

Objective-C Associated Objects

Add properties to objects in categories.

As a developer, I love coming across new methods or techniques that help make better, more readable code. Recently I was trying to find a better way of passing information from a method that creates a UIAlertView to the UIAlertView’s delegate method alertView:didDismissWithButtonIndex:. There is no userInfo dictionary for an alert view, and Apple specifically says not to subclass UIAlertView. What I’ve done in the past is create a property or class instance variable to temporarily hold the object I want to pass around. I don’t like this technique, it feels sloppy, but it gets the job done. Now behold the power of Objective-C Associated Objects.

Associated Objects

Associated objects have been around since iOS 3.1 and are a part of the Objective-C runtime. They allow you to associate objects at runtime. Basically, you can attach any object to any other object without subclassing. To begin using associated objects, all you need to do is import <objc/runtime.h> in the class where you want to use them. The relevant methods are the following:

void objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy)
id objc_getAssociatedObject(id object, void *key)
void objc_removeAssociatedObjects(id object)

object is the source object for the association, or in other words, it is the object that will point to the other object.
*key is the the key for the association, this can be any void pointer, anything that has a constant memory address is all you want.
value is the object you want to store or associate with the source object.
policy is a constant defining the type of reference, similar to the types you use when declaring properties. The possible values are:

enum {


Typically we don’t want to use objc_removeAssociatedObjects, but would rather use setAssociatedObject with a nil value to remove an association. According to Apple,
The main purpose of this function is to make it easy to return an object to a “pristine state”. You should not use this function for general removal of associations from objects, since it also removes associations that other clients may have added to the object. Typically you should use objc_setAssociatedObject with a nil value to clear an association.

In many cases you probably won’t have to worry about removing an association because when the source object is destroyed it will destroy the reference to the associated object.

Sample Use Case

In my case, I want to associate an NSIndexPath to a UIAlertView. Let me explain my use case a little further, you have probably come across a similar problem. I have a table view where I show a confirmation alert when the user tries to delete a row. Usually I wouldn’t put a confirmation on a delete, but sometimes it has serious implications (maybe you’re deleting a folder holding 100 records of something and deleting the folder deletes all those precious records).

The alert is created and displayed in the UITableViewDataSource method tableView:commitEditingStyle:forRowAtIndexPath:. At this point you have the indexPath you want to delete. Once you call -show on the alert, your class starts waiting for the UIAlertViewDelegate callback methodalertView:didDismissWithButtonIndex:. Once the user confirms, it enters the delegate method and you no longer know which indexPath you should delete.

Now I’m going to detail a number of solutions to this problem, each better than the last. I’m only going to show the relevant code though instead of the entire class because I’m using a very simple example. I just slightly modified the code that is generated for you when you create a new project with the master-detail template (without core data).

Original Solution

The original solution was to have a class level instance variable that holds the index path we want to delete. We would set the index path to delete in our commitEditingStyle method, and then retrieve it in alertView:didDismissWithButtonIndex.


@interface MasterViewController () <UIAlertViewDelegate> {
    NSMutableArray *_objects;
    NSIndexPath *_indexPathToDelete;


- (void)tableView:(UITableView *)tableView commitEditingStyle:
forRowAtIndexPath:(NSIndexPath *)indexPath
    if (editingStyle == UITableViewCellEditingStyleDelete) {
    	NSString *deleteMessage = @"Are you sure you want to delete this super important thing?";
        UIAlertView *deleteConfirmation = [[UIAlertView alloc] initWithTitle:@"Delete Row"
                                                           otherButtonTitles:@"Confirm", nil];
        _indexPathToDelete = indexPath;
        [deleteConfirmation show];


- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
    if (buttonIndex == 1) {
        [_objects removeObjectAtIndex:_indexPathToDelete.row];
        [_tableView deleteRowsAtIndexPaths:@[_indexPathToDelete] withRowAnimation:UITableViewRowAnimationFade];


This solution works, but why would we want to use this instance variable that is visible to the entire class? Only two methods have interest in this index path, and what if some other method messes with indexPathToDelete and we get some unexpected behavior. It would be better if we could confine this object to only the methods that care about it.

Acceptable Solution

Using the objective-c runtime methods we can associate the index path to the alert view. We will set the association in commitEditingStyle, and retrieve the index path in didDismissWithButtonIndex:.


#import <objc/runtime.h>

static char deleteKey;

@interface MasterViewController () <UIAlertViewDelegate> {
    NSMutableArray *_objects;


- (void)tableView:(UITableView *)tableView 
forRowAtIndexPath:(NSIndexPath *)indexPath
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *deleteMessage = @"Are you sure you want to delete this super important thing?";
        UIAlertView *deleteConfirmation = [[UIAlertView alloc] initWithTitle:@"Delete Row"
                                                           otherButtonTitles:@"Confirm", nil];
        objc_setAssociatedObject(deleteConfirmation, &deleteKey, indexPath, OBJC_ASSOCIATION_RETAIN);
        [deleteConfirmation show];


- (void)alertView:(UIAlertView *)alertView 
    if (buttonIndex == 1) {
        NSIndexPath *deletePath = objc_getAssociatedObject(alertView, &deleteKey);
        [_objects removeObjectAtIndex:deletePath.row];
        [_tableView deleteRowsAtIndexPaths:@[deletePath] 


As you can see, we no longer need the instance variable, but we use a new static char variable as the association key. The alert view holds a strong reference to the index path, so it persists from one method to the next as long as the alert view is still in memory. When the alert view is destroyed it will also destroy the index path associated with it. This makes the code clearer and confined to just the methods it is used in instead of having an instance variable that is available to the whole class. We can make this code even better though.

Better Solution

Associated Objects Category

You can create a category on NSObject that simplifies the objective-c runtime calls into a nice API you can use in your normal classes. You could expand on this, but a basic category would be as follows:


@interface NSObject (AssociatedObjects)
- (void)associateValue:(id)value withKey:(void *)key;
- (id)associatedValueForKey:(void *)key;



#import "NSObject+AssociatedObjects.h"
#import <objc/runtime.h>

@implementation NSObject (AssociatedObjects)

- (void)associateValue:(id)value withKey:(void *)key
    objc_setAssociatedObject(self, key, value, OBJC_ASSOCIATION_RETAIN);

- (id)associatedValueForKey:(void *)key
    return objc_getAssociatedObject(self, key);



Your view controller would then look like this…


#import "NSObject+AssociatedObjects.h"
static char deleteKey;

@interface MasterViewController () <UIAlertViewDelegate> {
    NSMutableArray *_objects;


- (void)tableView:(UITableView *)tableView 
forRowAtIndexPath:(NSIndexPath *)indexPath
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *deleteMessage = @"Are you sure you want to delete this super important thing?";
        UIAlertView *deleteConfirmation = [[UIAlertView alloc] initWithTitle:@"Delete Row"
                                                           otherButtonTitles:@"Confirm", nil];
        [deleteConfirmation associateValue:indexPath withKey:&deleteKey];
        [deleteConfirmation show];


- (void)alertView:(UIAlertView *)alertView 
    if (buttonIndex == 1) {
        NSIndexPath *deletePath = [alertView associatedValueForKey:&deleteKey];
        [_objects removeObjectAtIndex:deletePath.row];
        [_tableView deleteRowsAtIndexPaths:@[deletePath] 


I like this a little better because it abstracts out the runtime methods and gives you a nice interface you can use on any object. This accomplishes the same thing, but to me it is much more readable and feels better.

Awesome Solution

According to Apple docs:
The UIAlertView class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified.

Also according to Apple docs:
Categories can be used to declare either instance methods or class methods but are not usually suitable for declaring additional properties. It’s valid syntax to include a property declaration in a category interface, but it’s not possible to declare an additional instance variable in a category. This means the compiler won’t synthesize any instance variable, nor will it synthesize any property accessor methods. You can write your own accessor methods in the category implementation, but you won’t be able to keep track of a value for that property unless it’s already stored by the original class.

The only way to add a traditional property-backed by a new instance variable-to an existing class is to use a class extension, as described in ‘Class Extensions Extend the Internal Implementation.'”

With our newfound power, we will add a new property to UIAlertView without subclassing it. As you see in the documentation, it is perfectly valid to declare a property in the category interface, you just can’t create a new instance variable. We don’t need a new instance variable, we will just override the getter and setter of our property to store and retrieve the property by associating it to the alert view.

Let’s create a category on UIAlertView called DeleteConfirmation.

In UIAlertView+DeleteConfirmation.h

@interface UIAlertView (DeleteConfirmation)
@property (nonatomic) NSIndexPath *indexPathToDelete;


Now in UIAlertView+DeleteConfirmation.m

#import "UIAlertView+DeleteConfirmation.h"
#import "NSObject+AssociatedObjects.h"

@implementation UIAlertView (DeleteConfirmation)

- (void)setIndexPathToDelete:(NSIndexPath *)indexPathToDelete
    [self associateValue:indexPathToDelete withKey:@selector(indexPathToDelete)];

- (NSIndexPath *)indexPathToDelete
    return [self associatedValueForKey:@selector(indexPathToDelete)];



Thanks to Erica Sadun, who then credits Gwynne Raskind, for this bad-assery of using the property selector as the association key. According to them, this is valid because Apple’s selector implementation uses a fixed address.

Using the same example, after importing the new category, our view controller code becomes:


#import "UIAlertView+DeleteConfirmation.h"

@interface MasterViewController () <UIAlertViewDelegate> {
    NSMutableArray *_objects;


- (void)tableView:(UITableView *)tableView
forRowAtIndexPath:(NSIndexPath *)indexPath
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *deleteMessage = @"Are you sure you want to delete this super important thing?";
        UIAlertView *deleteConfirmation = [[UIAlertView alloc] initWithTitle:@"Delete Row"
                                                           otherButtonTitles:@"Confirm", nil];
        deleteConfirmation.indexPathToDelete = indexPath;
        [deleteConfirmation show];


- (void)alertView:(UIAlertView *)alertView 
    if (buttonIndex == 1) {
        NSIndexPath *deletePath = alertView.indexPathToDelete;
        [_objects removeObjectAtIndex:deletePath.row];
        [_tableView deleteRowsAtIndexPaths:@[deletePath] 


Beautiful. I love it. The index path to delete looks like any other property you would access.


Ok… maybe this is overkill for the example I gave, but I’m sure you will find other uses for it now that you know about it. It is a great weapon to have at your disposal, and it really helps you write much cleaner, self documenting code.

Source Reference : Press Here