Monday, December 16, 2013

EXC_BAD_ACCESS iOS ( iPhone ) OR iOS EXC_BAD_ACCESS causes crash



  1. Set "Enable Zombie Objects" means NSZombieEnabled. which helps to find cause sometime.  To set the same go to  Menubar > Product > Scheme > Edit Scheme.   This optionwill provide a warning in logs  when you try to access an object that has been deallocated. That is the cause for crash.
                             2.Find memory leaks in your app. Use Leak instrument for to find  memory leaks  
    1. Open the Leaks instrument Menubar > Xcode > Open Developer tool > Instrument 
    2. Choose your app from the Choose Target pop-up menu
    3. Click the Record button.
    4. Exercise your app to execute code, and click the Stop button when leaks are displayed.
    5. Click any leaked object that is identified in the Detail pane.
    6. Within the Extended Detail pane, double-click an instruction from your code.
    7. Click the Xcode icon in the Detail pane to open that code in Xcode.
3. Analyse code . Find possible chances part of code .s et a breakpoint in that part of code and step through until you find crashing

4.Another way is comment part by part code and check which part of code is causing it

Wednesday, December 11, 2013

"dynamic" or @dynamic keyword in Objective C iOS (iPhone)

tells the compiler that the getter and setter methods are implemented not by the class itself but somewhere else (like the superclass  will be provided at runtime). Used in CoreData
Uses for @dynamic are e.g. with subclasses of NSManagedObject (CoreData) or when you want to create an outlet for a property defined by a superclass that was not defined as an outlet.
Super class:
@property (nonatomic, retain) NSButton *someButton;
...
@synthesize someButton;
Subclass:
@property (nonatomic, retain) IBOutlet NSButton *someButton;
...

@dynamic someButton;

Monday, December 9, 2013

Retain Cycles in iOS (iPhone)

Retain Cycles

There are two Objects P and Q. P creates Q and retains it. Q has an instance variable that points to P, retaining it. So both retain each other.


Example:-

NSMutableArray *P = [NSMutableArray array];
NSMutableArray *Q = [NSMutableArray array];
[P addObject:Q];
[Q addObject:P];
Here both P and Q has strong refernce to each other. 
Every time a reference is deleted, the count goes down, when the count gets to zero, there are no references and so the object can be deleted.
Neither will get deallocated unless you manually break the cycle by e.g. removing one from the other.

Often avoided because they can make it tricky to ensure you haven't got memory leaks.



 If you have a cycle, You may have a group of objects and you don't want them any more, so you drop the only reference you have to these objects, but because there is a cycle the objects reference each other. This means their reference counts never go to zero, and they don't get deleted. This is a memory leak.

Garbage Collection handles this retain cycle without memory leaks

Garbage Collection in iOS (iPhone)

Garbage Collection
When you use the Cocoa garbage collection technology, it manages your application's memory for you.
There is no need to explicitly manage objects' retain counts to ensure
that they remain "live" or that the memory they take up is reclaimed when they are no longer used.

How the Garbage Collector Works (here collector or collection means GC)
When a collection is initiated, the collector initializes the set with all well-known root objects. The collector then recursively follows strong references from these objects to other objects, and adds these to the set. At the end of the process, all objects that are not reachable through a chain of strong references to objects in the root set are designated as "garbage." At the end of the collection sequence, the unreachable objects are finalized and immediately afterwards the memory they occupy is recovered.

The initial rootset of objectsis comprised of global variables,stack variables, and objects with external references. These objects are never considered as garbage. The root set is comprised of all objects reachable from root objects and all possible references found by examining the call stacks of every Cocoa thread.

As implied earlier, there are two types of reference between objects—strong and weak. A strong reference is visible to the collector, a weak reference is not.
 An important corollary is that simply because you have a strong reference to an object does not mean that that object will survive garbage collection, 
You can create a weak reference using the keyword __weak, or by adding objects to a collection configured to use weak references (such as NSHashTable and NSMapTable).

Enabling Garbage Collection
Garbage collection is an optional feature; you need to set an appropriate flag for the compiler to mark code as being GC capable. The compiler will then use garbage collector write-barrier assignment primitives within the Objective-C runtime. An application marked GC capable will be started by the runtime with garbage collection enabled.

There are three possible compiler settings:
No flag. This means that GC is not supported.
-fobjc-gc-only This means that only GC logic is present.Code compiled as GC Required is presumed to not use traditional Cocoa retain/release methods and may not be loaded into an application that is not running with garbage collection enabled.
-fobjc-gc This means that both GC and retain/release logic is present.Code compiled as GC Supported is presumed to also contain traditional retain/release method logic and can be loaded into any application.
You can choose an option most easily by selecting the appropriate build setting in Xcode, as illustrated in





Foundation Tools (like command line code)
In a Cocoa desktop application, the garbage collector is automatically started and run for you. If you are writing a Foundation tool, you need to start the collector thread manually using the function objc_startCollectorThread:
#import <objc/objc-auto.h>
int main (int argc, const char * argv[]) {
objc_startCollectorThread();
// your code
return 0;
}

You may want to occasionally clear the stack using objc_clear_stack() to ensure that nothing is falsely rooted on the stack. You should typically do this when the stack is as shallow as possible—for example, at the top of a processing loop.
You can also use objc_collect(OBJC_COLLECT_IF_NEEDED) to provide a hint to the collector that collection might be appropriate—for example, after you finish using a large number of temporary objects.


Finalizing objects
In a garbage-collected application, you should ideally ensure that any external resources held by an object (such as open file descriptors) are closed prior to an object’s destruction. If you do need to perform some you must ensure that there are strong 
Nib files
references to all top-level objects in a nib file (including for example, stand-alone controllers)—otherwise they will be collected operations just before an object is reclaimed, you should do so in a finalize method.
You can create a strong reference simply by adding an outlet to the File's Owner and connecting it to a top-level object

Triggering garbage collection
Cocoa automatically hints at a suitable point in the event cycle that collection may be appropriate.
The collector then initiates collection if memory load exceeds a threshold. Typically this should be sufficient to provide good performance. Sometimes, however, you may provide a hint to the collector that collection may be warranted—for example after a loop in which you create a large number of temporary objects. You can do this using the NSGarbageCollector method collectIfNeeded.

// Create temporary objects
NSGarbageCollector *collector = [NSGarbageCollector defaultCollector];
[collector collectIfNeeded];

Threading
Garbage collection is performed on its own thread—a thread is explicitly registered with the collector if it calls NSThread's currentThread method (or if it uses an autorelease pool). There is no other explicit API for registering a pthread with the collector.




Prune caches
The collector scans memory to find reachable objects, so by definition keeps the working set hot. You should therefore make sure you get rid of objects you don't need.

Avoid allocating large numbers of short-lived objects
Object allocation is no less expensive an operation in a garbage collected environment than in a reference-counted environment.

Compile GC-Only
In general, you should not try to design your application to be dual-mode (that is, to support both garbage collection and reference-counted environments). The exception is if you are developing frameworks and you expect clients to operate in either mode.

C++
In general, C++ code should remain unchanged: you can assume memory allocated from standard malloc zone. If you need to ensure the longevity of Objective-C objects, you should use CFRetain instead of retain.



Garbage collection offers some significant advantages over a manually reference-counted environment 
-simplifies the task of managing memory
-reduces the amount of code you have to write and maintain
-makes it easier to write multi-threaded code: you do not have to use locks to ensure the atomicity of accessor methods and you do not have to deal with per-thread autorelease pools
(Note that although garbage collection simplifies some aspects of multi-threaded programming, it does not automaticallymake your application thread-safe. For more about thread-safe application development, see Threading Programming Guide .)

Garbage collection does though have some disadvantages:
-application’s working set may be larger
-Performance may not be as good as if you hand-optimize memory management
-A common design pattern whereby resources are tied to the lifetime of objects does not work effectively under GC.
-You must ensure that for any object you want to be long-lived you maintain a chain of strong references to it from a root object, or resort to reference counting for that object.
-Not all frameworks and technologies support garbage collection

Performance
The performance characteristics of an application that uses garbage collection are different from those of an application that uses reference-counting
Garbage-collected application may have betterperformance, for example:
Multi-threaded applications may perform better with garbage collection because of better thread support;
Accessor methods are much more efficient (you can implement them using simple assignment with no locks);
Your application is unlikely to have leaks or stale references.

In other areas, however, performance may be worse:
-Allocation may be a significant consideration if your application allocates large numbers of (possibly short-lived) objects.
The working set may be larger—in particular, the overall heap can grow larger due to allocation outpacing collection.
The collector scans heap memory to find reachable objects, so by definition keeps the working set hot.This may be a significant consideration, particularly if your application uses a large cache.
The collector runs in a secondary thread. As such, a GC-enabled application will in almost all cases consume more CPU cycles than a reference-counted application.

source:-https://developer.apple.com/legacy/library/documentation/Cocoa/Conceptual/GarbageCollection/GarbageCollection.pdf

Wednesday, November 13, 2013

Version Mismatch - Neither CFBundleVersion nor CFBundleShortVersionString in the Info.plist match the version of the app set in iTunes Connect .

Thus is just warning message . It will not stop application  from submission.
If you want to correct the version you can reject current app from itunes.
But be careful when you change this version  review process will start over from the begining when you resubmit your binary.

Friday, April 5, 2013

extern "C" in objective C / extern "C" meaning


extern "C" void foo(int);
extern "C"
{
   void g(char);
   int i;
}

When C++ compiler compiles the function It mangles the function name fot to support function overloading.
extern C is used mainly to inform compiler compile this in c style (i.e.  do not do name mangling to function name.).

Mainly extern is used to when u have library compiled by C compiler. and want to add same in C++ code. When u compile it will get linking error because C++ compiler will mangle function name and C++ linker will not get the definition for the function name ( function definition is in C compiled library where function name is not mangled so.)

extern "C" with braces tells the C++ compiler do not mangle the function name.


Thursday, April 4, 2013

Blocks in objective c

Blocks are feature added to C, Objective and C++ basically to create an object(some structure in case of c) without data member and single function in it.
 They can be added to collections likeNSArray or NSDictionary. They can be passed around to methods or functions as if they were values. 
 They also have the ability to capture values from the enclosing scope, making them similar to closures or lambdas in other programming languages.

Block Syntax

^{

         NSLog(@"This is a block");

 }
braces indicate the start and end of the block.

Block with no argument taking and nothing returning:-
Ex:- here simpleBlock is a variable to store bloack its same like function pointer in C
void (^simpleBlock)(void);


simpleBlock = ^{

        NSLog(@"This is a block");

    };
You can also combine the variable declaration and assignment:
void (^simpleBlock)(void) = ^{

        NSLog(@"This is a block");

    };

After this assignment u can invoke the block as
 simpleBlock();
Like calling function on function pointer.

Note: If you attempt to invoke a block using an unassigned variable (a nil block variable), your app will crash.

Blocks Take Arguments and Return Values
Example
double (^multiplyTwoValues)(double, double);

^ (double firstValue, double secondValue) {

        return firstValue * secondValue;

    }

firstValue and secondValue refers to passing arguments to the block same like passing argument to function.


Combined as
double (^multiplyTwoValues)(double, double) =

                              ^(double firstValue, double secondValue) {

                                  return firstValue * secondValue;

                              };



    double result = multiplyTwoValues(2,4);


Blocks Can Capture Values from the Enclosing Scope

- (void)testMethod {

    int anInteger = 42;



    void (^testBlock)(void) = ^{

        NSLog(@"Integer is: %i", anInteger);

    };



    testBlock();

}


In this example, anInteger is declared outside of the block, but the value is captured when the block is defined.
Example
int anInteger = 42;



    void (^testBlock)(void) = ^{

        NSLog(@"Integer is: %i", anInteger);

    };



    anInteger = 84;



    testBlock();
output of the above program will be
Integer is: 42
It also means that the block cannot change the value of the original variable, or even the captured value (it’s captured as a const variable).




Use __block Variables to Share Storage
Use   __block storage type   when u want the value of captured variable within block should be change.   

Example:-
__block int anInteger = 42;



    void (^testBlock)(void) = ^{

        NSLog(@"Integer is: %i", anInteger);

    };



    anInteger = 84;



    testBlock();
output of this program will be 
Integer is: 84
It also means that the block can modify the original value, like this:
 __block int anInteger = 42;



    void (^testBlock)(void) = ^{

        NSLog(@"Integer is: %i", anInteger);

        anInteger = 100;

    };



    testBlock();

    NSLog(@"Value of original variable is now: %i", anInteger);

output will be
Integer is: 42

Value of original variable is now: 100

You Can Pass Blocks as Arguments to Methods or Functions
it’s common to pass blocks to functions or methods for invocation elsewhere. Just like passing function pointer on which passed function can call that function.
Blocks are also used for callbacks, defining the code to be executed when a task completes.
example:-
- (IBAction)fetchRemoteInformation:(id)sender {

    [self showProgressIndicator];



    XYZWebTask *task = ...



    [task beginTaskWithCallbackBlock:^{

        [self hideProgressIndicator];

    }];

}

The declaration for the beginTaskWithCallbackBlock: method shown in this example would look like this:
- (void)beginTaskWithCallbackBlock:(void (^)(void))callbackBlock;

The (void (^)(void)) specifies that the parameter is a block that doesn’t take any arguments or return any values. The implementation of the method can invoke the block in the usual way:
- (void)beginTaskWithCallbackBlock:(void (^)(void))callbackBlock {

    ...

    callbackBlock();

}

Method parameters that expect a block with one or more arguments are specified in the same way as with a block variable:
- (void)doSomethingWithBlock:(void (^)(double, double))block {

    ...

    block(21.0, 2.0);

}





A Block Should Always Be the Last Argument to a Method
- (void)beginTaskWithName:(NSString *)name completion:(void(^)(void))callback;

This makes the method call easier to read when specifying the block inline, like this:
    [self beginTaskWithName:@"MyTask" completion:^{

        NSLog(@"The task is complete");

    }];



More
Block objects are a C-level syntactic and runtime feature that allow you to compose function expressions that can be passed as arguments, optionally stored, and used by multiple threads.



You use a block when you want to create units of work (that is, code segments) that can be passed around as though they are values. Blocks offer more flexible programming and more power. You might use them, for example, to write callbacks or to perform an operation on all the items in a collection.




About

Powered by Blogger.