Thursday, September 26, 2013

XCode4.5.2 in error "can not init class"

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** + [Fraction <0x1000034f8> init]: cannot init a class object.

According to "Programming in Objective-C" in the fourth edition of the routine copied it, build and run when it was being given

Fraction * myFraction;
myFraction = [Fraction alloc];
myFraction = [Fraction init];

Then google a bit into

myFraction = [[Fraction alloc] init];

Will be successful, which is why it? Version of the problem or grammar?
Or other questions, please advise!

Reply:
With this one out on
myFraction = [Fraction alloc]; Then just allocated memory, and is not initialized. It is not so assigned.
Reply:
Oh, found the problem, copy the original code was wrong, and in the name of the class to write alloc time, time to write in the init instance name, did not pay attention, now understand, thanks for reply
Reply:
alloc method
According to Apple's official documentation. When the object is created, cocoa from the application's virtual address space to allocate enough memory for the object. cocoa will traverse all the member variables of the object by the type of member variables to calculate the amount of memory required.

When we alloc or allocWithZone method to create an object, cocoa will return a not "so early" over the object. In this process, cocoa addition to the above-mentioned application of a large enough memory, but also to do the following three things:

1. The new object's reference count (Retain Count) is set to 1.
(2) The new object isa member of the class object variable pointing to it.
3 The object of all other members of the new value of the variable is set to zero. (According to a member variable type, there may be zero or Nil means nil or 0.0)

isa member variable is defined in NSObject, so ensure that all objects with Cocoa this member variable. This variable can be achieved by means of Cocoa objects at runtime introspection (Introspection) function.
Reply:
init method

In most cases, we do hope that all member variables are zero, so the init method to do the real work so early, so that the value of the object's member variables in line with our program logic in the initialization state. For example, NSMutableString might then apply for an additional array of characters, used to dynamically modify the string.

init there is a need to pay attention. In some cases, init will cause the alloc original space is not enough, and the second allocation of memory space. Therefore, the following wording is wrong:

Copy the code
NSString * s = [NSString alloc]; [s init]; / / init here return address may change. s original pointer address may be invalid address.


To this end, Apple introduced a programming specification, so that we will write when alloc and init written on one line. So the above code is correct wording is

Copy the code
NSString * s = [[NSString alloc] init];

No comments:

Post a Comment