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.

-fsyntax-only
Check the code for syntax errors, but don’t do anything beyond that.
-fmax-errors=n
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.
-w
Inhibit all warning messages.
-Werror
Make all warnings into errors.
-Werror=
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.

-Wfatal-errors
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.

-Wpedantic
-pedantic
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.)

-pedantic-errors
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.
-Wall
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:

          -Waddress   
          -Warray-bounds=1 (only with -O2)  
          -Wc++11-compat  -Wc++14-compat
          -Wchar-subscripts  
          -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) 
          -Wbool-compare  
          -Wduplicated-cond  
          -Wcomment  
          -Wformat   
          -Wmain (only for C/ObjC and unless -ffreestanding)  
          -Wmaybe-uninitialized 
          -Wmissing-braces (only for C/ObjC) 
          -Wnonnull  
          -Wopenmp-simd 
          -Wparentheses  
          -Wpointer-sign  
          -Wreorder   
          -Wreturn-type  
          -Wsequence-point  
          -Wsign-compare (only in C++)  
          -Wstrict-aliasing  
          -Wstrict-overflow=1  
          -Wswitch  
          -Wtautological-compare  
          -Wtrigraphs  
          -Wuninitialized  
          -Wunknown-pragmas  
          -Wunused-function  
          -Wunused-label     
          -Wunused-value     
          -Wunused-variable  
          -Wvolatile-register-var 
          

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.

-Wextra
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.)

          -Wclobbered  
          -Wempty-body  
          -Wignored-qualifiers 
          -Wmissing-field-initializers  
          -Wmissing-parameter-type (C only)  
          -Wold-style-declaration (C only)  
          -Woverride-init  
          -Wsign-compare  
          -Wtype-limits  
          -Wuninitialized  
          -Wshift-negative-value  
          -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.
-Wchar-subscripts
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.
-Wcomment
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.
-Wno-coverage-mismatch
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.
-Wno-cpp
(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.

-Wformat
-Wformat=n
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.

-Wformat=1
-Wformat
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.
-Wno-format-contains-nul
If -Wformat is specified, do not warn about format strings that contain NUL bytes.
-Wno-format-extra-args
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.

-Wno-format-zero-length
If -Wformat is specified, do not warn about zero-length formats. The C standard specifies that zero-length formats are allowed.
-Wformat=2
Enable -Wformat plus additional format checks. Currently equivalent to -Wformat -Wformat-nonliteral -Wformat-security -Wformat-y2k.
-Wformat-nonliteral
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.
-Wformat-security
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.)
-Wformat-signedness
If -Wformat is specified, also warn if the format string requires an unsigned argument and the argument is signed and vice versa.
-Wformat-y2k
If -Wformat is specified, also warn about strftime formats that may yield only a two-digit year.
-Wnonnull
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.

-Wnull-dereference
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.

-Wmain
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 SOME_CONDITION_THAT_DOES_NOT_HOLD
            if (flagB)
          #endif
              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.

-Wmissing-braces
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.
-Wparentheses
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 ();
            else
              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 ();
                else
                  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.

-Wsequence-point
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 http://gcc.gnu.org/readings.html.

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

-Wno-return-local-addr
Do not warn about returning a pointer (or in C++, a reference) to a variable that goes out of scope after the function returns.
-Wreturn-type
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.

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

-Wshift-overflow=1
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.)
-Wshift-overflow=2
This warning level also warns about left-shifting 1 into the sign bit, unless C++14 mode is active.
-Wswitch
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.
-Wswitch-default
Warn whenever a switch statement does not have a default case.
-Wswitch-enum
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.
-Wswitch-bool
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.
-Wtrigraphs
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.
-Wunused-but-set-parameter
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.

-Wunused-but-set-variable
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.

-Wunused-function
Warn whenever a static function is declared but not defined or a non-inline static function is unused. This warning is enabled by -Wall.
-Wunused-label
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.
-Wunused-parameter
Warn whenever a function parameter is unused aside from its declaration.To suppress this warning use the unused attribute (see Variable Attributes).

-Wno-unused-result
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.
-Wunused-variable
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).

-Wunused-const-variable
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).

-Wunused-value
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.

-Wunused
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.

-Wuninitialized
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.

-Wmaybe-uninitialized
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;
                break;
              case 2: x = 4;
                break;
              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.

-Wunknown-pragmas
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.
-Wno-pragmas
Do not warn about misuses of pragmas, such as incorrect parameters, invalid syntax, or conflicts between pragmas. See also -Wunknown-pragmas.
-Wstrict-aliasing
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
-Wstrict-aliasing=n
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.

-Wstrict-overflow
-Wstrict-overflow=n
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.

-Wstrict-overflow=1
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.
-Wstrict-overflow=2
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.
-Wstrict-overflow=3
Also warn about other cases where a comparison is simplified. For example: x + 1 > 1 is simplified to x > 0.
-Wstrict-overflow=4
Also warn about other simplifications not covered by the above cases. For example: (x * 10) / 5 is simplified to x * 2.
-Wstrict-overflow=5
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.
-Wsuggest-attribute=[pure|const|noreturn|format]
Warn for cases where adding an attribute may be beneficial. The attributes currently supported are listed below.

-Wsuggest-attribute=pure
-Wsuggest-attribute=const
-Wsuggest-attribute=noreturn
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.
-Wsuggest-attribute=format
-Wmissing-format-attribute
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.

-Wsuggest-final-types
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.
-Wsuggest-final-methods
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.
-Wsuggest-override
Warn about overriding virtual functions that are not marked with the override keyword.
-Warray-bounds
-Warray-bounds=n
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.

-Warray-bounds=1
This is the warning level of -Warray-bounds and is enabled by -Wall; higher levels are not, and must be explicitly requested.
-Warray-bounds=2
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.
-Wbool-compare
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.

-Wduplicated-cond
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.

-Wframe-address
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.
-Wno-div-by-zero
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.
-Wsystem-headers
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.
-Wtautological-compare
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.

-Wtrampolines
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.
-Wfloat-equal
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.
-Wundef
Warn if an undefined identifier is evaluated in an #if directive.
-Wno-endif-labels
Do not warn whenever an #else or an #endif are followed by text.
-Wshadow
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.
-Wlarger-than=len
Warn whenever an object of larger than len bytes is defined.
-Wframe-larger-than=len
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.
-Wno-free-nonheap-object
Do not warn when attempting to free an object that was not allocated on the heap.
-Wstack-usage=len
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
    
-Wunsafe-loop-optimizations
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.
-Wplacement-new
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.
-Wpointer-arith
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.
-Wtype-limits
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.
-Wcast-qual
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';
-Wcast-align
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.
-Wwrite-strings
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.

-Wclobbered
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.
-Wconversion
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.
-Wdate-time
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.
-Wempty-body
Warn if an empty body occurs in an if, else or do while statement. This warning is also enabled by -Wextra.
-Wenum-compare
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.

-Wsign-compare
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.
-Wsign-conversion
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.
-Wfloat-conversion
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.
-Wno-scalar-storage-order
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.

-Wsizeof-pointer-memaccess
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.
-Wsizeof-array-argument
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.
-Wmemset-transposed-args
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.
-Waddress
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.
-Wlogical-op
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) { ... }
-Wlogical-not-parentheses
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.

-Waggregate-return
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.)
-Wno-aggressive-loop-optimizations
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.
-Wno-attributes
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.
-Wno-builtin-macro-redefined
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++.
-Wmissing-declarations
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.
-Wmissing-field-initializers
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.

-Wno-multichar
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.
-Wnormalized[=<none|id|nfc|nfkc>]
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.

-Wno-deprecated
Do not warn about usage of deprecated features. See Deprecated Features.
-Wno-deprecated-declarations
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.
-Wno-overflow
Do not warn about compile-time overflow in constant expressions.
-Wno-odr
Warn about One Definition Rule violations during link-time optimization. Requires -flto-odr-type-merging to be enabled. Enabled by default.
-Wopenmp-simd
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.
-Wpacked
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;
          };
-Wpacked-bitfield-compat
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.

-Wpadded
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.
-Wredundant-decls
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.
-Wno-inherited-variadic-ctor
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.
-Winline
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.

-Wno-int-to-pointer-cast
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.
-Winvalid-pch
Warn if a precompiled header (see Precompiled Headers) is found in the search path but can’t be used.
-Wlong-long
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.
-Wvariadic-macros
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.
-Wvarargs
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.
-Wvector-operation-performance
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.
-Wno-virtual-move-assign
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.
-Wvla
Warn if variable length array is used in the code. -Wno-vla prevents the -Wpedantic warning of the variable length array.
-Wvolatile-register-var
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.
-Wdisabled-optimization
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.
-Wstack-protector
This option is only active when -fstack-protector is active. It warns about functions that are not protected against stack smashing.
-Woverlength-strings
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.
Advertisements

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:

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

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:

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

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:

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

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="user.name" type="text" />
Hello {{user.name}}!

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: 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 {
   OBJC_ASSOCIATION_ASSIGN = 0,
   OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,
   OBJC_ASSOCIATION_COPY_NONATOMIC = 3,
   OBJC_ASSOCIATION_RETAIN = 01401,
   OBJC_ASSOCIATION_COPY = 01403
};

 

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:
(UITableViewCellEditingStyle)editingStyle 
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"
                                                                     message:deleteMessage
                                                                    delegate:self
                                                           cancelButtonTitle:@"Cancel"
                                                           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 
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
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"
                                                                     message:deleteMessage
                                                                    delegate:self
                                                           cancelButtonTitle:@"Cancel"
                                                           otherButtonTitles:@"Confirm", nil];
        objc_setAssociatedObject(deleteConfirmation, &deleteKey, indexPath, OBJC_ASSOCIATION_RETAIN);
        [deleteConfirmation show];
    }
}

...

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

 

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:

NSObject+AssociatedObjects.h

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

 

NSObject+AssociatedObjects.m

#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);
}

@end

 

Your view controller would then look like this…

 

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

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

...

- (void)tableView:(UITableView *)tableView 
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
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"
                                                                     message:deleteMessage
                                                                    delegate:self
                                                           cancelButtonTitle:@"Cancel"
                                                           otherButtonTitles:@"Confirm", nil];
        [deleteConfirmation associateValue:indexPath withKey:&deleteKey];
        [deleteConfirmation show];
    }
}

...

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

 

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;
@end

 

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)];
}

@end

 

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
 commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
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"
                                                                     message:deleteMessage
                                                                    delegate:self
                                                           cancelButtonTitle:@"Cancel"
                                                           otherButtonTitles:@"Confirm", nil];
        deleteConfirmation.indexPathToDelete = indexPath;
        [deleteConfirmation show];
    }
}

...

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

 

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

Conclusion

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

iDev : Essential Tools for iOS Developers

75 Essential Tools for iOS Developers

Source Reference : Here

If you were to go to a master woodworker’s shop, you’d invariably find a plethora of tools that he or she uses to accomplish various tasks.

In software it is the same. You can measure a software developer by how they use their tools. Experienced software developers master their tools. It is important to learn your current tools deeply, and be aware of alternatives to fill in gaps where your current ones fall short.

With that in mind, I present to you a gigantic list of tools. Some of these I use daily, others I see potential in. If you have more tools you’d like to see here, just make sure to add a comment.

I tried to categorize these the best I can. Some of the entries are websites, some are back-end services, but most are apps that you install. Not all of the apps are free, so I’ll make a note with a $ to denote that an app costs money.

And without further ado, we’ll start from the beginning of any project, and that

Inspiration

  • pttrns – A great library of iOS screen designs categories by task. If you want to see how other apps handle activity feeds, for instance, this is a great place to go see a bunch of examples.
  • TappGala – Another great collection of nice app designs. It’s not categorized by task, but is just a list of great apps to get inspiration from.
  • Cocoa Controls – A great list of components (code) that you can use in your iOS apps. Sometimes you’ll find great pieces of code that can save you time, other times you can just learn how other developers accomplish certain features. Subscribe to their weekly newsletter; all signal, little noise.
  • IICNS – A collection of really great icons. Get inspired, but don’t copy.
  • Dribbble – Some of the best digital designers post up their work for all to see. A treasure-trove of designs to look at.
  • Capptivate – a gallery of inspirational designs. Some contain animations. Thanks, @joaopmaia!

Design

  • Mocks ($) – An easy to use tool to create a quick mockup of an iOS app. Comes with a bunch of the default controls you can use to assemble something quickly.
  • Briefs ($) – A really useful app that allows you to create a mockup of an app and stitch them together so you can see the interaction. Deploy to a device so you can see what it feels like in your hand.
  • Acorn ($) – A strong competitor to Photoshop, only way cheaper. I find myself reaching for Photoshop less & less these days. Under active development.
  • Sketch ($) – A vector-based drawing tool that is increasingly useful these days, as screen sizes and pixel densities change. It is often helpful to design once and have the freedom to scale up & down as needed. Also sports a really powerful export system. For some example Sketch projects, check out Sketchmine. See my screencast on Sketch for a live demo.
  • iOS 7 PSD by Teehan+Lax – A super handy resource if you (or your designer) uses Photoshop. An iOS 6 version is also available.
  • Bjango’s Photoshop Actions – A definite time-saver if you use Photoshop to design iOS apps. One click access to resize canvases, scale by 200% (or 50%), set global lighting to 90º, and more. Their blog also has a bunch of useful Photoshop workflow tips.
  • xScope ($) – An indespensible swiss-army knife of tools such as guides, pixel loupes, screen rulers, and more. Want to know what color value that pixel is? Want to see how many pixels between a button and the window for a random Mac app? xScope has you covered. Also check out their companion iPhone app for mirroring designs you’re working on and seeing them in pixel-perfect glory on your iDevice.
  • Glyphish ($) – A fantastic collection of high quality icons for your iOS apps. Apple doesn’t provide a lot of built-in icons, so it’s handy to have a collection of icons covering all kinds of various concepts. I’m still looking for a use for that baby icon though. Glyphish comes in packs, and the latest pack has iOS 7 “thin line” icons which will be very handy when designing an iOS 7 app.
  • Fontastic Icons for iOS – An open source set of classes for utilizing icon fonts, such as Font Awesome in your iOS app. Quickly and easily have an icon in whatever pixel dimensions you require. Since fonts by nature can be scaled up and down with ease, this makes a really nice way to ship & use your icons without having to export multiple versions for the sizes you require.
  • PaintCode ($) – A vector-based drawing tool that exports your artwork as the equivalent Core Graphics source code. Awesome for learning how Core Graphics drawing works, but also incredibly handy if you want your drawing to be dynamic. See my screencast on PaintCode for a live demo.
  • Edge Insets ($) – A simple tool that helps you define your edge insets for repeatable images. Available on the Mac App Store.
  • LiveView – A remote screen viewer for iOS, making it easy to immediately see your designs on a device. Thanks, @_funkyboy!
  • Skala Preview ($) – Another excellent tool for quickly showing your designs off on a real device. The guys at Bjango are awesome and this app is deserving of the price. Thanks, jn40!

Source Control

  • Git – If you’re not using source control stop what you’re doing and rectify that. I use git for everything I do and love it.
  • Kaleidoscope ($) – The best diff/merge tool around. Does 3-way merges and is beautiful to look at. I use it every day.
  • p4merge – A free, ugly alternative to Kaleidoscope. Powerful 3-way merge, but good luck finding the download link. It’s hidden deeper in their site every time I look for it.
  • Git X – A simple, powerful GUI tool for visualizing git timelines and quickly & easily staging commits. I usually live in the Terminal for git usage, but fall back to this app when I need to stage hunks of changes into logical commits. This is a fork of the original (abandoned) GitX, which I found on this list of forks.
  • Source Tree – A free, full-featured Git application. I don’t use this because I favor the command line, but if a GUI tool is your cup-o-tea, check this app out.

Dissecting Apps

  • pngcrush – This little utility can crush & uncrush PNG files, which is handy when you want to view images contained in app bundled distributed in the App Store. Just open iTunes, view the local Apps list, and right click on any icon to Show in Finder. Once there, open up the app and you’ll see a bunch of PNG files, but you can’t view them. Using pngcrush you can extract the full version so it can be opened with Preview.
  • appcrush.rb – This handy little ruby script will automate the above process for all images. Just point it to a .app file on your disk and it will extract all the images to a folder on your desktop. Handy for seeing how apps on your phone accomplish certain designs. Check out my screencast on dissecting apps for a live demo.
  • Charles ($, free limited demo) – I don’t know what’s going on with the ugly UI or icon, but Charles is an essential tool for any developer. Charles acts as a proxy to allow you to inspect your network traffic to & from the iPhone Simulator. You can also inspect traffic from your device by setting your phone’s proxy to your Mac running Charles. With self-signed SSL certificates, request & response breakpoints, and request/response viewers, Charles is really amazingly powerful. A must-have tool. Again, my screencast on dissecting apps covers this well.

Editors

I know what you’re thinking, don’t all iOS developers use Xcode? Well mostly, yes. But with my love/hate relationship with Xcode, I believe there is tremendous value in considering alternatives.

  • AppCode – A full-fledged IDE from Jetbrains (makers of the excellent ReSharper for .NET). Immensely powerful refactorings & features that help you write code faster. Quickly identify dead code, automatically insert #import statements when you use related code, easily extract variables, methods, and classes. My only wish for this app is that it would instead be a plugin to Xcode.
  • Vim – Wait, vim? Really? Yes, there are folks who do all their Objective-C development in vim. I’m not one of these, but I am a fan of vim for Ruby development. As such, I’m a huge fan of…
  • Xvim – An Xcode plug-in that gives you vim keybindings. Works well, ‘nuff said.
  • OMColorSense – Another plugin for Xcode, this one gives you a small display of color when your cursor is on a line looking like: [UIColor redColor]. Clicking on this little color tab opens a color picker that you can change, and any change in color you make is reflected in the code by changing the line to [UIColor colorWithRed:… green:… blue:… alpha:… ]. When someone is watching me write code with this enabled, they invariably ask me, “Whoa! What was that?!”
  • KSImageNamed – Another Xcode plug-in, this one allows you to autocompleted image filenames from your bundle when typing [UIImage imageNamed:…]. Great way to avoid the inevitable typo that causes this method to return nil and you to subsequently waste 10 minutes trying to figure out why your images aren’t displaying.
  • CocoaPods Xcode Plugin – This plug-in adds a menu item for interacting with CocoaPods. Useful if you don’t like dropping to the command line.
  • Alcatraz Package Manager – An awesome meta plug-in that allows you to easily install other Xcode color schemes and plug-ins with a single click.
  • Code Runner ($) – a light-weight code-aware text editor that knows how to compile & run code in most languages. Want to test out a quick snippet of Objective-C code and don’t want to create an entire Xcode project to do it? Code Runner to the rescue.

Documentation

Ahhh, documentation, everyone’s favorite topic. Even still, documentation is really important to have, so pay attention so we can make your life easier.

  • appledoc – Want to automatically generate documentation that look’s like Apple’s? Look no further. Automatically inter-links symbols defined in your project as well as extracting discussion to output using specially formatted code-comments. Generates official docsets and HTML web sites.
  • Dash ($) – A must-have API documentation viewer and code snippet manager. This tool is really handy as it allows you to download & search API docs for all kinds of languages & frameworks with lightning speed. The fastest way to get access to the docs. I integrate Dash with Alfred to make searches even faster.

Dependency Management

Yes, there’s only one tool listed here. I didn’t want to include actual 3rd party libraries, as that would be a different list entirely. When it comes to dependency management, there’s only one game in town:

  • CocoaPods – The essential tool for Objective-C projects. Allows you to quickly & easily integrate 3rd party libraries into your application. It does so by creating a second static library project and automatically links this with your projects. There are thousands of pods available, and it’s easy to add support for libraries that you don’t own (or perhaps are private). I use CocoaPods in every single project I work on.

Diagnostics & Debugging

At some point our app is in the field and we need to understand better what’s going on, maybe to fix bugs or to improve performance.

  • Cocoa Lumberjack – a much more powerful NSLog, Cocoa Lumberjack offers advanced logging behaviors such as logging to rotated files, logging to the network, and filtering based on log level (info, debug, warn, error). Covered by NSScreencast Episode 61
  • DCIntrospect – crazy powerful tool that you’d link inside your app when running in debug and on the simulator. Once you do, you can press the spacebar to get some really helpful view debugging support. See exact dimensions of elements on the screen, print out view hierarchies, even nudge views horizontally or vertically.
  • Pony Debugger – another tool you’d use by embedding a library in your debug builds, Pony Debugger actually utilizes Chrome’s dev tools for seeing network requests coming out of the device, as well as a rudimentary Core Data browser. It’s hard to describe, but check out my screencast on Pony Debugger for more info.
  • Runscope ($) – Runscope is a service running online that can capture requests, log details, and give you valuable data about your API. Simple to set up, as it’s an HTTP pass-through API, all you need to change is your host name.
  • SimPholders – Quick, easy access to your simulator folders. Browse by iOS version, then app name and jump right to the folder in Finder.
  • Spark Inspector ($) – Debug your view hierarchy running on your app in debug mode, in 3D. This app really has to be seen to fully understand the value, but it can really help to understand what views are used to compose your app. Also contains a notification center inspector, so you can easily see what NSNotifications are firing and who is observing them. Another app to look at that is similar is Reveal.

Images

  • ImageAlpha – A Mac app that allows you to convert a 24-bit PNG with transparency to an 8-bit PNG with an alpha channel. Typically 8-bit PNGs don’t have an alpha channel, so if your image can be represented in 8-bits (say, a solid color button) you can save a lot on storage by converting the 24-bit PNG to 8-bit using ImageAlpha.
  • ImageOptim – Another Mac app that compresses PNGs in order to save space. Most PNG files can shave off a few % of the size, and sometimes you’ll shrink the files by 30% or more. Smaller images mean smaller app sizes and less memory used to load them at runtime.
  • Prepo – A little Mac app that can quickly resize artwork in all the various sizes you might need. Just drag a large icon file (say, 1024×1024) onto Prepo and watch it spit out 512×512 iTunesArtwork, 114×114 Icon@2x.png, and all the other sizes & filenames you’d expect.
  • Slender ($) – an awesome app that analyzes your app and finds all sorts of problems, such as missing retina artwork, unused images, image that could benefit from compression and more. Shave kilobytes off of your iPhone app by shedding unused images with Slender.

Core Data

  • Mogenerator – still a super useful tool for generating smart subclasses of your NSManagedObjects in your Core Data model. Some use Xcode for this, and resort to manually subclassing or creating categories in order to add logic to the models. Mogenerator runs as a quick pre-compile script to generate subclasses for you to use. It does this by creating an underscored version (_User) and a regular one for you to modify (User).
  • Base ($) – there will come a time when you need to inspect your actual Core Data sqlite database to see what’s going on. You can use the sqlite3 command line tool, but Base offers a nice looking GUI browser. Just don’t vomit when you see the database schema that Core Data created for you.
  • Core Data Editor ($) – for more advanced data anlysis, exploration, and modification you can use Core Data Editor. This app understands Core Data, so you’re working directly with the entities instead of database rows.

Back-end Services

Ultimately your iOS app will likely want to talk to a server to share data, fetch new content, send push notifications or whatever. While this can be accomplished manually, you might want a more drop-in solution.

  • Helios – Helios is an open-source framework that provides essential backend services for iOS apps, from data synchronization and push notifications to in-app purchases and passbook integration. Built on top of many open source ruby gems, so you can pick & choose and build your own stack if you so desire. Take a look at the Nomad CLI set of handy related tools as well.
  • Windows Azure Mobile Services – you can think of this sort of like a programmable database in the cloud. Create tables, run JavaScript on read, insert, delete to add additional functionality. Really easy support for push notifications as well.
  • Urban Airship – I’ve been using Urban Airship to deliver push notifications for a while now. Really easy to integrate with, and small usage is free.
  • Parse – This is another data-in-the-cloud service, but offers an impressive API and online data browser. We use Parse for a really small app and works well for that.

Analytics

There are other players here, but none that I’ve seen have been compelling enough to switch from flurry. I’m open to hearing suggestions, so let’s hear about ‘em in the comments.

  • Flurry – I’ve used flurry for a long time to provide useful analytics on the usage of my apps. Need to know when to stop supporting iOS 5? Flurry gives you the numbers to have a realistic conversation.

Deployment

  • Deploymate ($) – Need to support iOS 4 still, but you’re compiling with the iOS 6 SDK? Deploymate will warn you when you’re using symbols that don’t exist in your deployment target.
  • Cupertino – Part of the Nomad CLI tools, Cupertino gives you command line access to managing devices & profiles in the Apple Provisioning Portal. For example, just type ios devices:list to see the current list of devices in your account. Useful for automating lots of processes.
  • Hockey App ($) – A great service for managing the distribution of your ad-hoc builds. Testers can get a link to install new betas over the air. Also provides robust crash reporting so you can easily respond to crashes in your apps.
  • TestFlight – A free service, similar to Hockey App. We’ve used TestFlight with great success for easily distributing apps and collecting feedback from our users. My only wish is that they’d start charging for the service. Also includes analytics and crash reporting, but we don’t use those features.
  • iOS Simulator Cropper – A really easy way to snap images of the simulator, with or without status bar, with or without device chrome, etc. Great for taking App Store or just general marketing screenshots.
  • Status Magic ($) – Take better app store screenshots. Nothing makes your app look less crappy than an App Store screenshot that includes a low battery, or low signal. Status Magic gives you complete customization over what’s present in your status bar, including removing elements, changing the time to “9:41 AM” like Apple tends to do, and more.
  • Crashlytics – Excellent crash reporting for your apps in the field. Automatically uploads dSYMs on release builds so your crashes are automatically symbolicated and organized for you to focus on the most critical ones.

Testing

I don’t think we as a community focus enough on testing. There are great tools available to us, and most are so easy to use we have no real excuse not to write at least some tests for our apps.

  • Kiwi – A great Rspec-style testing framework for iOS. Built on top of SenTestingKit, so you just type ⌘U to run your specs. Also includes a completely robust mocking & stubbing library as well as assertions.
  • Specta – A light-weight BDD framework very similar to Kiwi, but the expectation syntax has one major benefit over Kiwi: everything is implicitly boxed like this: expect(items.count).to.equal(5). There’s no need to wrap 5 in an NSNumber like Kiwi does. Use in conjunction with Expecta for a bunch of useful matchers.

The following are all various ways of performing end-to-end acceptance tests. These tests will actually interact with your interface, touching buttons, scrolling, etc. By nature these will be slower and more brittle, but testing in broad strokes is certainly helpful to see if all of the pieces fit together properly.

Demos / Marketing

  • Reflector ($) – Wirelessly mirror your iOS device on your Mac using Air Play. Great for doing demos of applications on your computer.
  • Placeit – A great collection of high res photos of people using devices, but the screens are templates that you can insert your own screenshots into. Very cool, and great for displaying your app in a nice way on your website.

App Sales Reporting

Of course you want to be able to see how much money you’re making on your app, right? There are a few solutions for this, but here are a couple that work well:

  • App Viz 2 ($) – a really useful Mac app for tracking sales of your apps. You run it locally and it logs in and downloads your sales reports.
  • App Annie – an online sales reporting tool. I’m less comfortable giving my credentials to iTunes to a 3rd party, but it does keep the reports up to date for you so you don’t have to run an app locally. In the comments, Josh Brown suggests creating a different user for analytics in iTunes Connect, which is a really good idea.

Grab Bag

These tools don’t have a defined category above, but deserve a mention nonetheless.

  • Quick Radar – Submitting bug reports to Apple is our only way of making their tools better. If you’re frustrated by the lack of a feature, you should be submitting a bug report. If you come across a bug, you should be submitting a bug report. One has no right to complain if they have not yet filed a radar :). With that in mind, submitting bug reports via bugreporter feels like a trip back to 1995. Quick Radar is an awesome little app that makes submitting bug reports super easy. Sports automatic posting to open radar so others can see it, in addition to tweeting, and posting to App.net. I use this app several times per week.

Thanks 🙂

Keep Reading and Experiment on your code….

 

iDev: Design pattern are used on iOS Development other than MVC

Hi Friends,

Here the some list of design pattern with sort description

Image

What is Design Pattern?

A design pattern is a common solution to a software problem. They are helpful for speeding up problem solving, ensuring
that a developer doesn’t have to re-invent the wheel for every situation. They also give developers a common vocabulary with which to get across high-level ideas with minimal explanation and full understanding.

Design patterns are everywhere in iOS Developement,Because iOS is a fairly specific platform, developers often face similar problems over and over, so there are a few design patterns that are extremely common in iOS.

Here is a short list of design patterns used by software engineers:

  • Abstract Factory Pattern
  • Adaptor Pattern
  • Object Modeling Pattern
  • Chain of Responsibility Pattern
  • Command Pattern
  • Composite Pattern
  • Decorator Pattern
  • Façade Pattern
  • Iterator Pattern
  • Mediator Pattern
  • Memento Pattern
  • Model-View-Controller Pattern
  • Observer Pattern
  • Proxy Pattern
  • Receptionist Pattern
  • Singleton Pattern
  • Template Method Pattern
  • S.O.L.I.D. Programming

On iOS :

Abstract Factory

The Abstract Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. The client is decoupled from any of the specifics of the concrete object obtained from the factory.

Adapter

The Adapter design pattern converts the interface of a class into another interface that clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. It decouples the client from the class of the targeted object.

Chain of Responsibility

The Chain of Responsibility design pattern decouples the sender of a request from its receiver by giving more than one object a chance to handle the request. The pattern chains the receiving objects together and passes the request along the chain until an object handles it. Each object in the chain either handles the request or passes it to the next object in the chain.

Command

The Command design pattern encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. The request object binds together one or more actions on a specific receiver. The Command pattern separates an object making a request from the objects that receive and execute that request.

Composite

The Composite design pattern composes related objects into tree structures to represent part-whole hierarchies. The pattern lets clients treat individual objects and compositions of objects uniformly. The Composite pattern is part of the Model-View-Controller aggregate pattern.

Decorator

The Decorator design pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. As does subclassing, adaptation of the Decorator pattern allows you to incorporate new behavior without modifying existing code. Decorators wrap an object of the class whose behavior they extend. They implement the same interface as the object they wrap and add their own behavior either before or after delegating a task to the wrapped object. The Decorator pattern expresses the design principle that classes should be open to extension but closed to modification.

Facade

The Facade design pattern provides a unified interface to a set of interfaces in a subsystem. The pattern defines a higher-level interface that makes the subsystem easier to use by reducing complexity and hiding the communication and dependencies between subsystems.

Iterator

The Iterator design pattern provides a way to access the elements of an aggregate object (that is, a collection) sequentially without exposing its underlying representation. The Iterator pattern transfers the responsibility for accessing and traversing the elements of a collection from the collection itself to an iterator object. The Iterator defines an interface for accessing collection elements and keeps track of the current element. Different iterators can carry out different traversal policies.

Mediator

The Mediator design pattern defines an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. These objects can thus remain more reusable. A “mediator object” in this pattern centralizes complex communication and control logic between objects in a system. These objects tell the mediator object when their state changes and, in turn, respond to requests from the mediator object.

Memento

The Memento pattern captures and externalizes an object’s internal state—without violating encapsulation—so that the object can be restored to this state later. The Memento pattern keeps the important state of a key object external from that object to maintain cohesion.

Observer

The Observer design pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. The Observer pattern is essentially a publish-and-subscribe model in which the subject and its observers are loosely coupled. Communication can take place between the observing and observed objects without either needing to know much about the other.

Proxy

The Proxy design pattern provides a surrogate, or placeholder, for another object in order to control access to that other object. You use this pattern to create a representative, or proxy, object that controls access to another object, which may be remote, expensive to create, or in need of securing. This pattern is structurally similar to the Decorator pattern but it serves a different purpose; Decorator adds behavior to an object whereas Proxy controls access to an object.

Receptionist

The Receptionist design pattern addresses the general problem of redirecting an event occurring in one execution context of an application to another execution context for handling. It is a hybrid pattern. Although it doesn’t appear in the “Gang of Four” book, it combines elements of the Command, Memo, and Proxy design patterns described in that book. It is also a variant of the Trampoline pattern (which also doesn’t appear in the book); in this pattern, an event initially is received by a trampoline object, so-called because it immediately bounces, or redirects, the event to a target object for handling.

Singleton

The Singleton design pattern ensures a class only has one instance, and provides a global point of access to it. The class keeps track of its sole instance and ensures that no other instance can be created. Singleton classes are appropriate for situations where it makes sense for a single object to provide access to a global resource.

Template Method

The Template Method design pattern defines the skeleton of an algorithm in an operation, deferring some steps to subclasses. The Template Method pattern lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

Source: Cocoa Design Patterns.

Reference : Stackoverflow.

Image

Thanks 🙂 Keep Coding…

iConcepts: 12 Myths About Concurrency in Objective-C By Jiva

12 Myths About Concurrency in Objective-C By Jiva 

There’s lots of cases where new Objective-C programmers incorrectly apply threads or misunderstand their use. I often see code from well intentioned folks who use threads where they absolutely don’t need them. Consequently, I thought I would put together this list of 12 myths to help guide you along the way to the proper use of threads in your apps.

Myth #1: Threads will make my app faster!

This is probably the most common newbie programmer mistake. Thinking that threads will make your app faster.

They won’t. Your code will execute at exactly the same rate regardless of whether it’s threaded or not. The key advantage that threads provide is that, in the case of a multiple-core machine, they allow you to do two things at once. This can speed processing of certain operations, but only in cases where the different operations are parallelizable. That is, in cases where the operations do not rely on each other for any portion of their calculations.

Even in cases where your operations are parallelizable, if you do not have multiple cores, your code will actually run slower if you add threads, since the processor will be doing more context switches to handle your threads.

https://i2.wp.com/www.random-ideas.net/Dropbox/Threading.png

So, in fact, the cases where threading will actually improve the performance of your app are confined to a relatively small subset. Still, this subset is important and encompasses many common use cases. Unfortunately, too often threads are applied in areas where they are not needed and where they will not significantly improve performance. The effort required to get threaded code right is substantial, and you need to weigh the benefit to bullshit ratio involved. You should also always profile your app before adding threads. You may find that the use case which you think is causing you problems in fact is not. Measure twice and cut once.

Myth #2: Threads will make my code simpler.

Writing thread safe code is hard. It’s seductive to think that if you could spin specific operations off into background threads, they become easier to manage because you no longer have to deal with things like callbacks, and asynchronicity.

The fact is, that adding threading to a complex app will only make it much, much more complicated. There’s an old saying that goes:

Without threads you have n problems. But with threads you have n+1 problems.

Or, as I like to say:

With threads you have n! problems!

Not only will you still have to deal with all your normal coding problems, you’ll also have to deal with things like locking, synchronization, queuing changes. Your code really becomes a lot more difficult to manage when you add threads.

Myth #3: I need threads to solve my problems with blocking I/O.

This common misconception comes from the fact that there are several synchronous methods on some of the foundation classes such as NSString and NSData which allow you to download content from the Internet. These methods, such as+stringWithContentsOfURL: are tremendously convenient, but block the current thread. Using them is as simple as:

NSString *myStr = [NSString 
                     stringWithContentsOfURL:urlToMyData];

Obviously, you’d never want to block the main thread, so a conscientious coder will often (wrongly) imagine that spinning this operation off into a background thread is a good way to still use these convenient methods. The fact is that this is a bad idea.

Threads can only be terminated when they are checking some kind of control variable and can thus be triggered to exit, such as:

while(keepRunning)
{
    NSString *myStr = [NSString 
                     stringWithContentsOfURL:urlToMyData];
}

Since the +stringWithContentsOfURL method blocks, the keepRunning variable will never get checked. So how do you stop this thread? The fact is, you don’t. There is simply no way to terminate a blocked thread.

This issue alone should be enough to make you walk away, but in case its not, consider that you also have no way to specify a timeout for these methods, you can no longer properly handle complex handshaking such as from authentication, and you lose the ability to interpret status codes that might be returned when accessing the resource.

Because of all this, you should never use these methods.

You might be saying to yourself right now “But I don’t need to worry about those things, I have a very simple use case, and my data will always be available.”

The answer is no. Never use these methods! there’s no need to! The Foundation classes, NSURLConnection and NSURLRequest provide more than enough functionality to do the job properly without blocking and without using threads.

Before I came to Objective-C I wrote a lot of C++, most of it networking code. I know how hard it is to get networking code right. One surprising lesson I learned is that even when writing services that had to handle many incoming connections, threads are almost always still the wrong answer. If you imagine a case where you’re handling hundreds of connections, you really don’t want to spawn and manage hundreds of threads. You’re really much better treating your sockets as a pool and handling I/O on them that way.

Much research has been done on this subject, but one of the best resources I have found is from Dan Kegel in his article, “The C10K problem.” You can go read those docs, and bleed yourself into socket code for the next 5 years of your career, or you can take my word for it: Apple knows what they’re doing here, and they got it right.NSURLConnection and NSURLRequest will handle 90% of the networking needs of most developers.

(How to handle the other 10%? That’s another post!)

A lot of developers will also make the mistake of prematurely optimizing networking code like this when they have large resources they have to download. They imagine that they need to run even NSURLConnection in a background thread. This couldn’t be further from the truth.

NSURLConnection is extremely efficient at downloading even very large files. I’ve never seen a file it couldn’t handle. It will not block your runloop. Your own code, processing those large files, may block the runloop and need to be threaded, but the actual downloading will not.

Myth #4: NSOperation means I don’t have to think about threading issues.

Just because you’re using NSOperation doesn’t mean your code is magically thread safe. NSOperation provides no thread safety facilities whatsoever. It simply provides an easier way to spawn and manage threads by abstracting away the details of the thread itself. All you need to provide is the code that actually does the work. NSOperation does the rest for you.

What this means in terms of our discussion here is that everything I’ve said about writing thread safe code still applies and code you write as part of your NSOperations still needs to be thread safe.

Myth #5: Atomic properties makes my code thread safe

As we’ve already seen, thread safety is a complex subject full of dark alleys and pitfalls. At it’s most fundamental level, even just reading a value from memory can be fraught with peril. When making your classes thread safe, you have to account for both these low level fundamental operations as well as higher logical level relationships, such as setting different variables within your class.

Atomic properties addresses only the issue of accessing your property values. An atomic property insures that the setter of a property cannot modify the property while it is being retrieved. Basically, when you use atomic properties, the accessors generated by the compiler wind up looking something (roughly) like the following:

 //@property(retain) UITextField *userName;
 //Generates roughly

 - (UITextField *) userName {
     UITextField *retval = nil;
     @synchronized(self) {
         retval = [[userName retain] autorelease];
     }
     return retval;
 } - (void) setUserName:(UITextField *)userName_ {
     @synchronized(self) {
       [userName_ retain];
       [userName release];
       userName = userName_;
     }
 }

(via objective c – Atomic vs nonatomic properties – Stack Overflow)

When using an atomic property, you will never run into the circumstance where you receive a corrupt value from the getter due to the setter changing the value while you are getting it. This doesn’t mean that the setter won’t change the value after you have received it, and so, thus, it does not fully insure thread safety. It only addresses one part of the full thread safety picture.

Myth #6: Serial operation queues are not threaded.

Just because you’ve made an NSOperationQueue serial by setting it’smaxConcurrentOperationCount to 1 doesn’t mean that the operations you add to that queue will not be run in a background thread. In fact, with the exception of the built-in queue you get from the NSOperationQueue class method, +mainQueue(NSOperationQueue Class Reference) all queues will run in a background thread. In the case of the +mainQueue it actually returns the queue associated with the main thread of your application and runs it on that queue. The main queue is serial.

Myth #7: GCD makes threading easy.

Along these same lines, GCD also does not make working with threads any safer or easier than any other thread mechanism. GCD’s role in Objective-C threading is actually for the purposes of managing thread pools. It’s job is to correctly determine the appropriate number of threads to use for your hardware based on the number of processors and cores your machine has. Although you can use the low level GCD API to add your operations directly to GCD, NSOperation provides a higher level abstraction to the very same mechanism, and is, generally, the preferred way to do it.

Myth #8: Threads Can Be Terminated Safely From Outside The Thread

It’s actually not possible to terminate a thread if the thread itself doesn’t want to be terminated. This is not entirely obvious, but it’s true. This is why most threaded operations utilize a flag to tell them when to exit prematurely. For example:

-(void)myThreadedOperation
{
    while(continueToRun && ![self allStuffIsDone])
    {
        // do some stuff...
    }
}

In this case, we have a background thread that is doing a series of operations. When all the operations are done, it sets the returns true from -allStuffIsDone and exits the loop. However, it also has a flag called continueToRun which its checking on each loop. This flag can be set by an external thread to cause this thread to exit after any iteration. If your background operations will take a long time, you probably want to include a similar design pattern.

Myth #9: I can safely throw exceptions in threads.

What happens when an exception is thrown in Objective-C and not caught? Usually, a crash. 1 What happens when an exception is thrown in a background thread and not caught? The answer is, the one thing worse than a crash: undefined behavior. It might crash… It might crash the whole app… It might crash just the thread… No one knows! It’s undefined. Your thread might even crash, and your app continue running. What do you think your app will do if it expected that thread to later either still be running or have finished?

Although I wouldn’t say that you can’t throw exceptions in threads at all, the important thing to know is that if you do, and it doesn’t get caught, the end result for your app is very bad.

Fortunately, Objective-C doesn’t use a lot of exceptions. So I don’t advocate putting generic exception handlers at the top of all your threaded operations. I point this out more as a “thing to know”. That exceptions can be dangerous in threads, and to be careful when working with code that does throw exceptions.

Myth #10: I can update my gui from background threads.

This one is fairly well known, but worth mentioning anyway. Cocoa and CocoaTouch, the GUI frameworks used on Mac OS and iOS respectively, are not thread safe. You must never update your GUI from a background thread. Whenever you need to trigger a GUI update from a background thread, you should do so on the main thread. Here’s an example of how to do this using the main queue and a block:

[[NSOperationQueue mainQueue] addOperationWithBlock:^
    {
        [self.tableView reloadData];
    }];

Myth #11: Notifications from background threads are executed on the main thread.

Notifications are nothing more than a set of method calls. So when a notification occurs, your notification handler will be called from the thread upon which the notification was triggered. This has some interesting implications.

For example, when you’re saving Core Data objects in a background thread, this notification will be sent from that background thread. Ordinarily, this is a great notification to watch for to update your UI when changes occur. Of course, we already talked about how you can’t update your UI from a background thread, but in addition to this, most of Core Data itself is also not thread safe2. In this case, the objects sent with the notification using the NSInsertedObjectsNSUpdatedObjects, andNSDeletedObjects keys in the userInfo dictionary cannot cross threads, so you can’t use them directly, even if you forward the notification to the main thread.

To handle this problem, you need to use the NSManagedObjectContext method, -mergeChangesFromDidSaveNotification: in the thread of the context which is receiving the notification so it can merge the changes. To do this, you can use themainQueue again like I showed you before:

[[NSOperationQueue mainQueue] addOperationWithBlock:^
    {
        [self.ctx mergeChangesFromContextDidSaveNotificaton:
                                     inNotification];
    }];

Myth #12: I shouldn’t use threads

Given all these hazards, you might think that you should never use threads. This is not the case. Threads are a useful tool, but like any tool, they have to be respected.

Threads are like the tablesaw of the Objective-C wood shop. They cause more application injuries than all other technologies combined. There’s times, however, when they’re really the best tool for the job! The important things to remember when using threads are:

  • Keep your thread’s data isolated.
  • Simplify the algorithms you intend to use in threads. Make them the “simplest thing that can possibly work.”
  • Learn the API used for insuring thread safety like it’s the back of your hand. Things like NSLock, @synchronized, NSRecursiveLock, etc.

  1. You can install an unhanded exception handler to change this behavior. 
  2. NSManagedObjectContext for example, can’t cross threads either. This is probably worthy of a post all of it’s own someday! 

Reference : Go Here

iPhonegap: Developing a PhoneGap Application

Tutorial: Developing a PhoneGap Application

Reference : Here

In this tutorial, you create a fully functional employee directory application with PhoneGap. You will learn:

  • How to use different local data storage strategies.
  • How to use several PhoneGap APIs such as Geolocation, Contacts, and Camera.
  • How to handle specific mobile problems such as touch events, scrolling, styling, page transitions, etc.
  • How to build an application using a single page architecture and HTML templates.
  • How to build (compile and package) an application for 6 platforms using PhoneGap Build.

To complete this tutorial, all you need is a code editor, a modern browser, and a connection to the Internet. A working knowledge of HTML and JavaScript is assumed, but you don’t need to be a JavaScript guru.

Setting Up

  1. Download the assets for the workshop here.
  2. Unzip the file anywhere on your file system.
  3. If your code editor allows you to “open a directory”, open the phonegap-workshop-master directory.
  4. Follow the instructions below.
Step-by-step solution files are also available here.

Part 1: Choosing a Local Storage Option


Step 1: Explore different persistence mechansisms

Open the following files in phonegap-workshop-master/js/storage, and explore the different persistence stores they define:

  1. memory-store.js (MemoryStore)
  2. ls-store.js (LocalStorageStore)
  3. websql-store.js (WebSqlStore)

Step 2: Test the application with different persistence mechanisms

To change the local persistence mechanism for the application:

  1. In index.html: add a script tag for the corresponding .js file: memory-store.jsls-store.js, or websql-store.js.
  2. In js/main.js: Instantiate the specific store in the initialize() function of the app object: MemoryStoreLocalStorageStore, or WebSqlStore.
  3. To test the application, open index.html in your browser, or simply double-click index.html on your file system. Type a few characters in the search box to search employees by name. Clicking an employee link doesn’t produce any result at this time.

Part 2: Building with PhoneGap Build


  1. If you don’t already have one, create an account on http://build.phonegap.com.
  2. Click the “new app” button to create a new application on PhoneGap Build.
  3. Either point to a GitHub repository where you push your code for this workshop, or zip up your phonegap-workshop directory and upload it to PhoneGap Build.
  4. Click the Ready to build button.
    The iOS button will immediately turn red because the iOS build requires that you upload your Apple Developer certificate and an application provisioning profile. You can find more information here if you haven’t already signed up for the Apple Developer Program. If you don’t have an iOS device, or if you are not ready to upload your developer certificate, you can skip step 5 and keep running the application in the browser or a non iOS device.
  5. To upload your Apple developer certificate and your application provisioning profile:
    • Click the red iOS button.
    • Select “add a key” in the “No key selected” dropdown.
    • Provide a title for your developer certificate/provisioning profile combination (for example: EmployeeDirectory), select your developer certificate and provisioning profile, enter your developer certificate password, and click “submit key”.
    • Go back to the list of apps. Click the iOS button for your application again. Select your newly added key in the iOS dropdown. The iOS build will start automatically.
  6. When the build process completes, use a QR Code reader app to install the Employee Directory application on your device.

To fine tune your build preferences:

  1. In the phonegap-workshop directory, create a file namedconfig.xml file defined as follows (make the necessary adjustments for id, author, etc.):
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    <?xml version="1.0" encoding="UTF-8"?>
    <widget xmlns       = "http://www.w3.org/ns/widgets"
            xmlns:gap   = "http://phonegap.com/ns/1.0"
            id          = "org.coenraets.employeedirectory"
            versionCode = "10"
            version     = "1.1.0">
        <name>Employee Directory</name>
        <description>
            A simple employee directory application
        </description>
        <author href="http://coenraets.org" email="ccoenraets@gmail.com">
            Christophe Coenraets
        </author>
        <feature name="http://api.phonegap.com/1.0/camera"/>
        <feature name="http://api.phonegap.com/1.0/contacts"/>
        <feature name="http://api.phonegap.com/1.0/file"/>
        <feature name="http://api.phonegap.com/1.0/geolocation"/>
        <feature name="http://api.phonegap.com/1.0/media"/>
        <feature name="http://api.phonegap.com/1.0/network"/>
    </widget>
  2. If you used the GitHub approach, sync with GitHub and click the Update Code button in PhoneGap Build.
    If you used the zip file approach, zip up your phonegap-workshop directory and upload the new version to PhoneGap Build
There are many other parameters you can specify in config.xml to configure the build process. See the documentation for config.xmlhere.

Part 3: Using Native Notification


A default webview alert gives away the fact that your application is not native. In this section, we set up the basic infrastructure to display native alerts when the application is running on a device, and fall back to default browser alerts when running in the browser.

  1. In index.html, add the following script tag (as the first script tag at the bottom of the body):
    1
    <script src="phonegap.js"></script>

    This instructs PhoneGap Build to inject a platform specific version of phonegap.js at build time. In other words, phonegaps.js doesn’t need to be (and shouldn’t be) present in your project folder.

  2. In main.js, define a function named showAlert() inside the app object. If navigator.notification is available, use its alert() function. Otherwise, use the default browser alert() function.
    1
    2
    3
    4
    5
    6
    7
    showAlert: function (message, title) {
        if (navigator.notification) {
            navigator.notification.alert(message, null, title, 'OK');
        } else {
            alert(title ? (title + ": " + message) : message);
        }
    },
  3. Test the notification logic by displaying a message when the application store has been initialized: Pass an anonymous callback function as an argument to the constructor of the persistence store (the store will call this function after it has successfully initialized). In the anonymous function, invoke the showAlert() function.
    1
    2
    3
    4
    5
    6
    7
    initialize: function() {
        var self = this;
        this.store = new MemoryStore(function() {
            self.showAlert('Store Initialized', 'Info');
        });
        $('.search-key').on('keyup', $.proxy(this.findByName, this));
    }
  4. Test the application: When you run the application in the browser, you should see a standard browser alert. When you run the application on your device, you should see a native alert.

Part 4: Setting Up a Single Page Application


A single page application is a web application that lives within a single HTML page. The “views” of the application are injected into- and removed from the DOM as needed as the user navigates through the app. A single page application architecture is particularly well suited for mobile apps:

  • The absence of continual page refreshes provides a more fluid / closer to native experience.
  • The UI is entirely created at the client-side with no dependency on a server to create the UI, making it an ideal architecture for applications that work offline.

In this section, we set up the basic infrastructure to turn Employee Directory into a single page application.

  1. In index.html: remove the HTML markup inside the body tag (with the exception of the script tags).
  2. In main.js, define a function named renderHomeView() inside the app object. Implement the function to programmatically add the Home View markup to the body element.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    renderHomeView: function() {
        var html =
                "<div class='header'><h1>Home</h1></div>" +
                "<div class='search-view'>" +
                "<input class='search-key'/>" +
                "<ul class='employee-list'></ul>" +
                "</div>"
        $('body').html(html);
        $('.search-key').on('keyup', $.proxy(this.findByName, this));
    },
  3. Modify the initialize() function of the app object. In the anonymous callback function of the store constructor, call the renderHomeView() function to programmatically display the Home View.
    1
    2
    3
    4
    5
    6
    initialize: function() {
        var self = this;
        this.store = new MemoryStore(function() {
            self.renderHomeView();
        });
    }

Part 5: Using Handlebar Templates


Writing HTML fragments in JavaScript and programmatically inserting them into the DOM is tedious. It makes your application harder to write and harder to maintain. HTML templates address this issue by decoupling the UI definition (HTML markup) from your code. There are a number of great HTML template solutions: Mustache.js, Handlebar.js, and Underscore.js to name a few.

In this section, we create two templates to streamline the code of the Employee Directory application. We use Handlebar.js but the smae result can be achieved using the other HTML template solutions.

Modify index.html as follows:

  1. Add a script tag to include the handlebar.js library:
    1
    <script src="lib/handlebars.js"></script>
  2. Create an HTML template to render the Home View. Add this script tag as the first child of the body tag:
    1
    2
    3
    4
    5
    <script id="home-tpl" type="text/x-handlebars-template">
        <div class='header'><h1>Home</h1></div>
        <div class='search-bar'><input class='search-key' type="text"/></div>
        <ul class='employee-list'></ul>
    </script>
  3. Create an HTML template to render the employee list items. Add this script tag immediately after the previous one:
    1
    2
    3
    4
    5
    <script id="employee-li-tpl" type="text/x-handlebars-template">
        {{#.}}
        <li><a href="#employees/{{this.id}}">{{this.firstName}} {{this.lastName}}<br/>{{this.title}}</a></li>
        {{/.}}
    </script>

Modify main.js as follows:

  1. In the initialize() function of the app object, add the code to compile the two templates defined above:
    1
    2
    this.homeTpl = Handlebars.compile($("#home-tpl").html());
    this.employeeLiTpl = Handlebars.compile($("#employee-li-tpl").html());
  2. Modify renderHomeView() to use the homeTpl template instead of the inline HTML:
    1
    2
    3
    4
    renderHomeView: function() {
        $('body').html(this.homeTpl());
        $('.search-key').on('keyup', $.proxy(this.findByName, this));
    },
  3. Modify findByName() to use the employeeLiTpl template instead of the inline HTML:
    1
    2
    3
    4
    5
    6
    findByName: function() {
        var self = this;
        this.store.findByName($('.search-key').val(), function(employees) {
            $('.employee-list').html(self.employeeLiTpl(employees));
        });
    },
  4. Test the application.

Part 6: Creating a View Class


It’s time to provide our application with some structure. If we keep adding all the core functions of the application to the app object, it will very quickly grow out of control. In this section we create a HomeView object that encapsulates the logic to create and render the Home view.

Step 1: Create the HomeView Class

  1. Create a file called HomeView.js in the js directory, and define a HomeView class implemented as follows:
    1
    2
    3
    4
    var HomeView = function(store) {
    }
  2. Add the two templates as static members of HomeView.
    1
    2
    3
    4
    5
    6
    7
    var HomeView = function(store) {
    }
    HomeView.template = Handlebars.compile($("#home-tpl").html());
    HomeView.liTemplate = Handlebars.compile($("#employee-li-tpl").html());
  3. Define an initialize() function inside the HomeView class. Define a div wrapper for the view. The div wrapper is used to attach the view-related events. Invoke the initialize() function inside the HomeView constructor function.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    var HomeView = function(store) {
        this.initialize = function() {
            // Define a div wrapper for the view. The div wrapper is used to attach events.
            this.el = $('<div/>');
            this.el.on('keyup', '.search-key', this.findByName);
        };
        this.initialize();
    }
    HomeView.template = Handlebars.compile($("#home-tpl").html());
    HomeView.liTemplate = Handlebars.compile($("#employee-li-tpl").html());
  4. Move the renderHomeView() function from the app object to the HomeView class. To keep the view reusable, attach the html to the div wrapper (this.el) instead of the document body. Because the function is now encapsulated in the HomeView class, you can also rename it from renderHomeView() to just render().
    1
    2
    3
    4
    this.render = function() {
        this.el.html(HomeView.template());
        return this;
    };
  5. Move the findByName() function from the app object to the HomeView class.
    1
    2
    3
    4
    5
    this.findByName = function() {
        store.findByName($('.search-key').val(), function(employees) {
            $('.employee-list').html(HomeView.liTemplate(employees));
        });
    };

Step 2: Using the HomeView class

  1. In index.html, add a script tag to include HomeView.js (just before the script tag for main.js):
    1
    <script src="js/HomeView.js"></script>
  2. Remove the renderHomeView() function from the app object.
  3. Remove the findByName() function from the app object.
  4. Modify the initialize function() to display the Home View using the HomeView class:
    1
    2
    3
    4
    5
    6
    initialize: function() {
        var self = this;
        this.store = new MemoryStore(function() {
            $('body').html(new HomeView(self.store).render().el);
        });
    }

Part 7: Adding Styles and Touch-Based Scrolling


Step 1: Style the Application

  1. Add the Source Sans Pro font definition to the head of index.html
    1
    <script src="css/source-sans-pro.js"></script>

    Source Sans Pro is part of the free Adobe Edge Web Fonts.

  2. Add styles.css to the head of index.html
    1
    <link href="css/styles.css" rel="stylesheet">
  3. In index.html, modify the home-tpl template: change the search-key input type from text to search.
  4. Test the application. Specifically, test the list behavior when the list is bigger than the browser window (or the screen)

Step 2: Native Scrolling Approach

  1. Modify the home-tpl template in index.html. Add a div wrapper with a scroll class around the ul element with a scroll:
    1
    2
    3
    4
    5
    <script id="home-tpl" type="text/x-handlebars-template">
        <div class='header'><h1>Home</h1></div>
        <div class='search-bar'><input class='search-key' type="search"/></div>
        <div class="scroll"><ul class='employee-list'></ul></div>
    </script>
  2. Add the following class definition to css/styles.css:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    .scroll {
        overflow: auto;
        -webkit-overflow-scrolling: touch;
        position: absolute;
        top: 84px;
        bottom: 0px;
        left: 0px;
        right: 0px;
    }
If the platforms you target support touch-based scrolling of fixed regions, this approach is all you need (you can skip step 3 below). If not, you’ll need to implement a programmatic approach, typically with the help of a library such as iScroll.

Step 3: iScroll Approach

  1. Add a script tag to include the iscroll.js library:
    1
    <script src="lib/iscroll.js"></script>
  2. In HomeView.js, modify the findByName() function: Instantiate an iScroll object to scroll the list of employees returned. If the iScroll object already exists (), simply refresh it to adapt it to the new size of the list.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    this.findByName = function() {
        store.findByName($('.search-key').val(), function(employees) {
            $('.employee-list').html(HomeView.liTemplate(employees));
            if (self.iscroll) {
                console.log('Refresh iScroll');
                self.iscroll.refresh();
            } else {
                console.log('New iScroll');
                self.iscroll = new iScroll($('.scroll', self.el)[0], {hScrollbar: false, vScrollbar: false });
            }
        });
    };
More information on iScroll is available here.

Part 8: Highlighting Tapped or Clicked UI Elements


  1. In styles.css, add a tappable-active class definition for tapped or clicked list item links. The class simply highlights the item with a blue background:
    1
    2
    3
    4
    li>a.tappable-active {
        color: #fff;
        background-color: #4286f5;
    }
  2. In main.js, define a registerEvents() function inside the app object. Add a the tappable_active class to the selected (tapped or clicked) list item:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    registerEvents: function() {
        var self = this;
        // Check of browser supports touch events...
        if (document.documentElement.hasOwnProperty('ontouchstart')) {
            // ... if yes: register touch event listener to change the "selected" state of the item
            $('body').on('touchstart', 'a', function(event) {
                $(event.target).addClass('tappable-active');
            });
            $('body').on('touchend', 'a', function(event) {
                $(event.target).removeClass('tappable-active');
            });
        } else {
            // ... if not: register mouse events instead
            $('body').on('mousedown', 'a', function(event) {
                $(event.target).addClass('tappable-active');
            });
            $('body').on('mouseup', 'a', function(event) {
                $(event.target).removeClass('tappable-active');
            });
        }
    },
  3. Invoke the registerEvents() function from within the app object’s initialize() function.
  4. Test the application.

Part 9: View Routing


In this section, we add an employee details view. Since the application now has more than one view, we also add a simple view routing mechanism that uses the hash tag to determine whether to display the home view or the details view for a specific employee.

Step 1: Create the employee template

Open index.html and add a template to render a detailed employee view:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script id="employee-tpl" type="text/x-handlebars-template">
    <div class='header'><a href='#' class="button header-button header-button-left">Back</a><h1>Details</h1></div>
    <div class='details'>
        <img class='employee-image' src='img/{{firstName}}_{{lastName}}.jpg' />
        <h1>{{firstName}} {{lastName}}</h1>
        <h2>{{title}}</h2>
        <span class="location"></span>
        <ul>
            <li><a href="tel:{{officePhone}}">Call Office<br/>{{officePhone}}</a></li>
            <li><a href="tel:{{cellPhone}}">Call Cell<br/>{{cellPhone}}</a></li>
            <li><a href="sms:{{cellPhone}}">SMS<br/>{{cellPhone}}</a></li>
        </ul>
    </div>
</script>

Step 2: Create the EmployeeView class

  1. Create a file called EmployeeView.js in the js directory, and define an EmployeeView class implemented as follows:
    1
    2
    3
    4
    var EmployeeView = function() {
    }
  2. Add the template as a static member of EmployeeView.
    1
    2
    3
    4
    5
    6
    var EmployeeView = function() {
    }
    EmployeeView.template = Handlebars.compile($("#employee-tpl").html());
  3. Define an initialize() function inside the HomeView class. Define a div wrapper for the view. The div wrapper is used to attach the view related events. Invoke the initialize() function inside the HomeView constructor function.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    var EmployeeView = function(employee) {
        this.initialize = function() {
            this.el = $('<div/>');
        };
        this.initialize();
     }
    EmployeeView.template = Handlebars.compile($("#employee-tpl").html());
  4. Define a render() function implemented as follows:
    1
    2
    3
    4
    this.render = function() {
        this.el.html(EmployeeView.template(employee));
        return this;
    };
  5. In index.html, add a script tag to include EmployeeView.js (just before the script tag for main.js):
    1
    <script src="js/EmployeeView.js"></script>

Step 3: Implement View Routing

  1. In the app’s initialize() function, define a regular expression that matches employee details urls.
    1
    this.detailsURL = /^#employees\/(\d{1,})/;
  2. In the app’s registerEvents() function, add an event listener to listen to URL hash tag changes:
    1
    $(window).on('hashchange', $.proxy(this.route, this));
  3. In the app object, define a route() function to route requests to the appropriate view:
    • If there is no hash tag in the URL: display the HomeView
    • If there is a has tag matching the pattern for an employee details URL: display an EmployeeView for the specified employee.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    route: function() {
        var hash = window.location.hash;
        if (!hash) {
            $('body').html(new HomeView(this.store).render().el);
            return;
        }
        var match = hash.match(app.detailsURL);
        if (match) {
            this.store.findById(Number(match[1]), function(employee) {
                $('body').html(new EmployeeView(employee).render().el);
            });
        }
    }
  4. Modify the initialize() function to call the route() function:
    1
    2
    3
    4
    5
    6
    7
    8
    initialize: function() {
        var self = this;
        this.detailsURL = /^#employees\/(\d{1,})/;
        this.registerEvents();
        this.store = new MemoryStore(function() {
            self.route();
        });
    }
  5. Test the application.

Part 10: Using the Location API


In this section, we add the ability to tag an employee with his/her location information. In this sample application, we display the raw information (longitude/latitude) in the employee view. In a real-life application, we would typically save the location in the database as part of the employee information and show it on a map.

The code below works when running the application as a PhoneGap app on your device. It should also work in Chrome on the desktop when the page is served with the http:// protocol, and in Firefox, regardless of the protocol (http:// or file://).
  1. In index.html, add the following list item to the employee-tpl template:
    1
    <li><a href="#" class="add-location-btn">Add Location</a></li>
  2. In the initialize() function of EmployeeView, register an event listener for the click event of the Add Location list item:
    1
    this.el.on('click', '.add-location-btn', this.addLocation);
  3. In EmployeeView, define the addLocation event handler as follows:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    this.addLocation = function(event) {
        event.preventDefault();
        console.log('addLocation');
        navigator.geolocation.getCurrentPosition(
            function(position) {
                $('.location', this.el).html(position.coords.latitude + ',' + position.coords.longitude);
            },
            function() {
                alert('Error getting location');
            });
        return false;
    };
  4. Test the Application

Part 11: Using the Contacts API


In this section, we use the PhoneGap Contacts API to provide the user with the ability to add an employee to the device’s contact list.

The code below only works when running the application on your device as a PhoneGap app. In other words, you can’t test it in a browser on the desktop.
  1. In index.html, add the following list item to the employee template:
    1
    <li><a href="#" class="add-contact-btn">Add to Contacts</a></li>
  2. In the initialize() function of EmployeeView, register an event listener for the click event of the Add to Contacts list item:
    1
    this.el.on('click', '.add-contact-btn', this.addToContacts);
  3. In EmployeeView, define the addToContacts event handler as follows:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    this.addToContacts = function(event) {
        event.preventDefault();
        console.log('addToContacts');
        if (!navigator.contacts) {
            app.showAlert("Contacts API not supported", "Error");
            return;
        }
        var contact = navigator.contacts.create();
        contact.name = {givenName: employee.firstName, familyName: employee.lastName};
        var phoneNumbers = [];
        phoneNumbers[0] = new ContactField('work', employee.officePhone, false);
        phoneNumbers[1] = new ContactField('mobile', employee.cellPhone, true); // preferred number
        contact.phoneNumbers = phoneNumbers;
        contact.save();
        return false;
    };
  4. Test the Application

Part 12: Using the Camera API


In this section, we use the PhoneGap Camera API to provide the user with the ability to take a picture of an employee, and use that picture as the employee’s picture in the application. We do not persist that picture in this sample application.

The code below only works when running the application on your device as a PhoneGap app. In other words, you can’t test it in a browser on the desktop.
  1. In index.html, add the following list item to the employee template:
    1
    <li><a href="#" class="change-pic-btn">Change Picture</a></li>
  2. In the initialize() function of EmployeeView, register an event listener for the click event of the Change Picture list item:
    1
    this.el.on('click', '.change-pic-btn', this.changePicture);
  3. In EmployeeView, define the changePicture event handler as follows:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    this.changePicture = function(event) {
        event.preventDefault();
        if (!navigator.camera) {
            app.showAlert("Camera API not supported", "Error");
            return;
        }
        var options =   {   quality: 50,
                            destinationType: Camera.DestinationType.DATA_URL,
                            sourceType: 1,      // 0:Photo Library, 1=Camera, 2=Saved Photo Album
                            encodingType: 0     // 0=JPG 1=PNG
                        };
        navigator.camera.getPicture(
            function(imageData) {
                $('.employee-image', this.el).attr('src', "data:image/jpeg;base64," + imageData);
            },
            function() {
                app.showAlert('Error taking picture', 'Error');
            },
            options);
        return false;
    };
  4. Test the Application

Part 13: Sliding Pages with CSS Transitions


  1. Add the following classes to styles.css:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    .page {
        position: absolute;
        width: 100%;
        height: 100%;
        -webkit-transform:translate3d(0,0,0);
    }
    .stage-center {
        top: 0;
        left: 0;
    }
    .stage-left {
        left: -100%;
    }
    .stage-right {
        left: 100%;
    }
    .transition {
        -moz-transition-duration: .375s;
        -webkit-transition-duration: .375s;
        -o-transition-duration: .375s;
    }
  2. Inside the app object, define a slidePage() function implemented as follows:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    slidePage: function(page) {
        var currentPageDest,
            self = this;
        // If there is no current page (app just started) -> No transition: Position new page in the view port
        if (!this.currentPage) {
            $(page.el).attr('class', 'page stage-center');
            $('body').append(page.el);
            this.currentPage = page;
            return;
        }
        // Cleaning up: remove old pages that were moved out of the viewport
        $('.stage-right, .stage-left').not('.homePage').remove();
        if (page === app.homePage) {
            // Always apply a Back transition (slide from left) when we go back to the search page
            $(page.el).attr('class', 'page stage-left');
            currentPageDest = "stage-right";
        } else {
            // Forward transition (slide from right)
            $(page.el).attr('class', 'page stage-right');
            currentPageDest = "stage-left";
        }
        $('body').append(page.el);
        // Wait until the new page has been added to the DOM...
        setTimeout(function() {
            // Slide out the current page: If new page slides from the right -> slide current page to the left, and vice versa
            $(self.currentPage.el).attr('class', 'page transition ' + currentPageDest);
            // Slide in the new page
            $(page.el).attr('class', 'page stage-center transition');
            self.currentPage = page;
        });
    },
  3. Modify the route() function as follows:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    route: function() {
        var self = this;
        var hash = window.location.hash;
        if (!hash) {
            if (this.homePage) {
                this.slidePage(this.homePage);
            } else {
                this.homePage = new HomeView(this.store).render();
                this.slidePage(this.homePage);
            }
            return;
        }
        var match = hash.match(this.detailsURL);
        if (match) {
            this.store.findById(Number(match[1]), function(employee) {
                self.slidePage(new EmployeeView(employee).render());
            });
        }
    },

    Thanks , Keep Coding 🙂

iConcept : What is DOM ?

 

What is DOM (Document Object Model): Tree and Node Structure of HTML Page

The Document Object Model (DOM) defines a standard way for accessing and manipulating HTML documents. The DOM presents an HTML document as a TREE-STRUCTURE. The DOM is a W3C (World Wide Web Consortium) standard. The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.

The Document Object Model (DOM) is the model that describes how all elements in an HTML page, like input fields, images, paragraphs etc., are related to the topmost structure: the document itself.
DOM: The Tree and Node Structure
The HTML DOM views an HTML document as a tree-structure. The tree structure is called a node-tree. In the DOM, everything in an HTML document is a node. All nodes can be accessed through the tree. Their contents can be modified or deleted, and new elements can be created.
Note: The Root Node of DOM Tree is DOCUMENT.
document.documentElement – returns the root node of the document
document.body – gives direct access to the <body> tag
The nodes in the node tree have a hierarchical relationship to each other. On the basis of hierarchy, Nodes can be divided into three categories:
1. Parent Nodes
2. Child Nodes
3. Sibling Nodes:
  Child Nodes on the same level are called siblings (brothers or sisters).
Example:
<p>This is a paragraph</p>
Here “p” is parent node and ‘This is a paragraph’ is a child node.
Note:
1. In a node tree, the top node is called the root
2. Every node, except the root, has exactly one parent node
3. A node can have any number of children
4. A leaf is a node with no children
5. Siblings are nodes with the same parent
Nodes can also be classified as:
1. Element Nodes: Every HTML element is an element node
2. Text Nodes: The text in the HTML elements are text nodes. In the HTML DOM the value of the text node can be accessed by the innerHTML property.
3. Attribute Nodes: Every HTML attribute is an attribute node
4. Comment Nodes: Comments are also treated as nodes in DOM.
5. Document Node: It is the parent node of DOM.. The entire document is a document node
Example:
<p align=”right”>This is a paragraph</p>
Here “p” is element node, ‘This is a paragraph” is a text node and “align” is the attribute node.
Node Properties
In the HTML DOM, each node is an object.Objects have methods and properties that can be accessed and manipulated by JavaScript. Three important node properties are:
1. nodeName
2. nodeValue
3. nodeType
The nodeName Property
The nodeName property specifies the name of a node.
1. nodeName is read-only
2. nodeName of an element node is the same as the tag name
3. nodeName of an attribute node is the attribute name
4. nodeName of a text node is always #text
5. nodeName of the document node is always #document
Note: nodeName always contains the uppercase tag name of an HTML element.
The nodeValue Property
1. The nodeValue property specifies the value of a node.
2. nodeValue for element nodes is undefined
3. nodeValue for text nodes is the text itself
4. nodeValue for attribute nodes is the attribute value
The nodeType Property
The nodeType property returns the type of node. nodeType is read only.
The most important node types are: Element Node, Text Node, Attribute Node, Comment Node and Document Node
HTML DOM Methods:
x.getElementById(id) – get the element with a specified id
x.getElementsByTagName(name) – get all elements with a specified tag name
x.appendChild(node) – insert a child node to x
x.removeChild(node) – remove a child node from x
Note: In the list above, x is a node object (HTML element or node, say document).
HTML DOM Properties
x.innerHTML – the text value of x
x.nodeName – the name of x
x.nodeValue – the value of x
x.parentNode – the parent node of x
x.childNodes – the child nodes of x
x.attributes – the attributes nodes of x
Note: In the list above, x is a node object (HTML element or node, say <p>).
Reference : Click Here

 

iConcept: GET vs POST

 GET vs POST: Which one is better? A 10 point comparison
1. Data Size Restriction in GET: There is a character restriction of 255 in the URL. This is mostly the old browsers restriction and new ones can handle more than that. But we can’t be sure that all our visitors are using new browsers. So when we show a text area or a text box asking users to enter some data, then there will be a problem if more data is entered. This restriction is not there in POST method. We can transfer unlimited data using POST. In PHP by default 8MB of data can be transferred. (can be changed by setting the post_max_size in the php.ini file)
2. Data Type Restriction in GET: As the data transfers through address bar ( URL ) there are some restrictions in using space, some characters like ampersand ( & ) etc in the GET method of posting data. We have to take special care for encoding (while sending) and decoding (while receiving) data if such special characters are present.
3. Security: In GET method data gets transferred to the processing page in name value pairs as a query string in URL, so it is exposed and can be easily traced by visiting history pages of the browser. Data is always submitted in the form of text. So any login details with password should never be posted by using GET method. On the other hand, POST is much more secure. In case of POST, all the name value pairs are submitted in the Message Body of the request.
4. Speed: GET is faster than POST.
5. Bookmarking: There are some special cases where advantage of using GET method is, one can store the name value pairs as bookmark and directly use them by bypassing the form. But you cannot bookmark using POST method.
6. If POST method is used and if the page is refreshed it would prompt before the request is resubmitted but it would not prompt if GET method is used.
7. Uploading files through input type file is possible in POST but not with GET method.
8. There are chances for data lost after server encoding in GET method but no data loss occurs in case of POST method.
9. GET uses STACK method for passing form variables while POST method uses HEAP method for passing form variables.
10. GET can store up to 18 form variables but there is no limit in case of POST method.
Reference : Click Here
Thanks :), Keep Coding:)

iConcept : Dropbox Alternatives and Competitors: Dropbox vs Other Online File Sharing and Storage Tools

Dropbox Alternatives and Competitors: Dropbox vs Other Online File Sharing and Storage Tools

Dropbox is a big name in the online file sharing and storage market. But there are a lot of alternatives and competitors of dropbox present in the online file sharing and storage market.
As there are some security and safety concerns with dropbox, people are searching for alternatives to dropbox to store their data online. A lot of competitors of dropbox are there in software market. We will have a detailed discussion on various alternatives to dropbox and competitors of dropbox. We will mainly focus on the features of Microsoft Live Mesh, Spider Oak, SugarSync, Wuala, Amazon Cloud Drive, Box, Syncplicity, Cubby, Huddle,  Egnyte, ShareFile, TeamDrive, Cloudme, CX etc. These are giving very tough competition to dropbox in syncing data with various devices or networks, online storage space, security and safety settings, encrypted data backup and recovery, media streaming etc.
Here goes the list of Alternatives to Dropbox: Dropbox Competitors
1. Microsoft Live Mesh: Microsoft’s file syncing tool works really well in the background. You can use Live Mesh just for local syncing and/or 5GB of SkyDrive’s online storage space (out of SkyDrive’s 25GB max). As you might expect, Live Mesh has some unique benefits for Windows users: you can remote control your Live Sync connected Windows computer (similar to Remote Desktop Connection) and sync Microsoft Office and Internet Explorer program settings. SkyDrive is also where Office Web Apps online documents are stored, so you get that integration as well.
Storage: Up to 25 GB Free, per SkyDrive Account
Desktop Support: Windows Vista SP2 or later, Mac OSX 10.5 or later
Browser Support: IE 7 or later preferred
Mobile Clients: None
2. SpiderOak: Besides its really strong “zero knowledge” security features, SpiderOak is very versatile: it can sync not only your desktop or mobile device but your external drive or network volume as well—so you can use it to keep your desktop, laptop, and USB thumb drive in sync, for example. SpiderOak offers a lot of information about your backups, uploads, and syncs, so you always feel in control of your data. Refer a friend and you get an additional 1GB more free space (up to 50GB max for the free referral space).
Storage: 2 GB Free, with Personal and Enterprise Plans Available
Desktop Support: PCs with Windows XP or greater, Mac 10.5 or later, and the more popular Linux distributions
Browser Support: Most modern Web browsers
Mobile Clients: iPhone and iPad with iOS 4, Android 2 or later, Blackberry 4 or later
3. SugarSync: SugarSync does what Dropbox does, but lacks the LAN sync and strong API support. It makes up for that in more features for media streaming, mobile syncing (including auto syncing photos and folders from Android devices), and folders selection and permissions/passwords settings. SugarSync’s web interface has a bit more functionality than Dropbox, with its separation of photos from files and also a very useful direct editing feature where you can edit files from within the webapp. You get a generous 5GB free to start with and can earn 500MB more space for each referral.
Storage: 5 GB Free, with Personal and Enterprise Plans Available
Desktop Support: PCs with Windows XP or later and Mac Desktops 10.4 or later
Browser Support: IE, Firefox 3 or later, Safari 4 or later, Chrome
Mobile Clients: iOS 4, Android 2 or later, Blackberry OS 4 or later, Windows Phone 7, and Symbian
4. Wuala: From Swiss storage manufacturer LaCie, Wuala, like SpiderOak, offers locally encrypted data backup and syncing. Although the 1GB of free storage space is on the low end to start with, Wuala has a unique way to earn additional storage: you can buy more space or exchange unused storage on your computer (e.g., empty space on an external drive) for more storage on Wuala.
5. Amazon Cloud Drive: Amazon’s drive offering is particularly attractive if you’re looking for a way to store your music library. They recently added Safari support, so if you’re on an iPhone or iPad you can now use the service. If you’re already set up with a Cloud Drive account, and have some music in it, just point Safari to the Cloud Player sign in page and you’ll see the desktop interface on your iOS device. Sign into your account and you’ll see the desktop interface on your iOS device.
On the downside, there’s no sync service or automated way to add your non-music files. It’s all manual upload and download. This is a fair place to hold your music library, but not useful for much else, given the options available today. Also, being forced to manually upload files via a Web browser gives the product a rushed and unfinished feel. However, it’s hard to complain about a free place to store your music. If you’re looking for a good place to store and stream your music library and can use some rudimentary non-music file storage as well, then Amazon Cloud Drive may work for you.
Storage: 5 GB Free, or 20 GB free with purchase of an album from the Amazon MP3 store
Desktop Support: Any OS that supports Flash
Browser Support: Any browser with Flash 9 or 10, newest browser versions preferred but not required
Mobile Clients: Android 2 or later, and browser support for Apple devices with iOS 4
6. Box: Box.net offers 5 GB of free cloud storage with a 25-MB file size limit. Storage is accessible by only one user, and access to your data via mobile app also is free. Box.net provides paid options for 25 GB and 50 GB at $10 and $20 per month, respectively, with 1-GB file size limits each.
Box.net offers up to 500 GB of shared storage, the most among the products within this roundup, with a collaborative toolset and workspace for up to three users for $15 per user, per month. Enterprise customers with needs beyond three users are encouraged to call Box.net for pricing. The features and functionality offered here are best suited to enterprise customers. Box.net’s complete set of collaborative tools, larger shared storage allotments, and associated costs are geared toward businesses with distributed work teams.
Storage: 5 GB Free
Desktop Support: Windows Vista SP2 or later, Mac OSX 10.5 or later
Browser Support: Mobile browser–Web Kit compatible
Mobile Clients: iOS 4.0 or later, Android 2.0 or later
7. Syncplicity: Syncplicity offers the same sync and share features of Dropbox with a decided enterprise slant. For example, admins can control which devices can access cloud storage inside or outside the company. Data retention policies can help admins find and remove documents that violate company data protection policies.
In a nod to the existing data protection measures in a large enterprise that allows an admin to wipe the data on connected laptop, Syncplicity also provides a way to wipe a user account for computers and mobile devices. The service uses audited security encryption technologies such as SOC 1 and standards such as the Department of Defense’s DoD 5220.22. Finally, the admin console is more robust than some; accounts can be pre-configured for access to specific files and folders for employee groups.
8. Cubby: The name might not make you think of an industrial strength cloud service, but Cubby-from the same company that makes the LogMeIn remote access tool-is a sure step above Dropbox. All user files are protected using SSL encryption; each user gets a separate encryption key. (In a few weeks, Cubby will release a beta for an optional high-security mode that will store encryption keys off-line so that only the user has access to the key.) During a data transfer between users, encryption keys form a tight bond between the two endpoints.
One interesting differentiator for Cubby is that information is stored in a data center owned and operated by LogMeIn, not Amazon or another third party. Like LogMeIn itself, Cubby works on the desktop and through a mobile app in addition to working through any browser.
9. Huddle: Huddle is more than just a place to keep files. The new service, designed for the enterprise, is more like a collaborative environment. This is also one of the strengths of the service in terms of security; repositories are organized according to workgroups and for those inside and outside the company.
Because the service is not designed to be a cloud storage service, the system tracks all documents and transfers. Admins can look up the rights to any document, check who has ownership and see how the document has been distributed in the organization. They can even see a history of comments on documents. Like LogMeIn, Huddle uses a company-owned data center that is ISO 27001 certified. The company conducts regular penetration testing and use enterprise-class firewalls.
10. Egnyte: Like most of the cloud storage systems listed here, Egnyte includes the usual admin console and file encryption options, but several unique feature make this cloud storage portal worth considering. Admins can assign permissions on a more granular level-down to sub-folders within sub-folders.
While other storage tools provide desktop and mobile apps, Egnyte also provides a way to create a mapped network drive or access from FTP. There’s also a way to generate an audit report showing permission and encryption levels. An enterprise version provides up to 3TB of storage and an unlimited number of users, while a unique “server sync” feature creates a sync between a server and the cloud.
11. ShareFile: Another smart alternative to Dropbox, ShareFile (now owned by Citrix) is a stark departure from consumer-level features. IT admins can use a unique “poison pill” option that sets an expiration point for any file. They can also perform a remote data wipe for any computer or mobile device.
12. TeamDrive: TeamDrive is a more secure version of online file sharing services and it uses AES-256 algorithm for encryption plus the public key feature makes it totally reliable and one of the best Dropbox alternative. It is ideal for Private users, small companies, corporations and supports all the platforms like  iOS, Linux and Windows. You also get a a free storage advantage over Dropbox with it’s 10 GB free online storage space. In addition you can also choose between hosted services, your own server or pre-installed TeamDrive cloud.
13. Cloudme: The feature that distinguishes this DropBox alternative from other listed so far is the creative Web Desktop, that allows you to have your own Desktop in the Cloud. You can then customize and increase productivity of your own Web OS by installing apps and create a working environment. This also enables you to to directly listen to your own music, look at images and edit photos. The Cloudme.com supports all the platforms including iOS and Android which means you can also directly Back-up and share information from you smartphones and mobile devices. The email support, MSN, ICQ, Google Talk, Yahoo and AIM integration makes this best Dropbox alternatives which is further accentuated with its free 3GB stirage space.
14. CX: A more social and interactive way to share files using cloud service, the Cx.com provides a free 10GB storage and a neat interface. You can Sync your files to just about every platform including  iOS,Mac, Windows, Kindle and Android but that’s not what differentiates it from the rest of DropBox alternatives. The ability to comment on shared files, add friends, create groups, and then share your files publicly or privately is what makes this one of the best DropBox Alternatives.
Reference : Here
Thanks :), Keep Coding:)