开发者

Meaning of following code

I have a sample app which i downloaded from net

In t开发者_JAVA百科his i was unable to understand following code

UILocalNotification *localNotif = [[UILocalNotification alloc] init];

if (localNotif == nil) 
    return;

also

  if (!array1) 
        return;

does this code means if object does not exists then return.....

HELP


In Cocoa, an initialiser will either return an object pointer if the call was successful, or a nil if it was unable to create the object.

Both cases are checking for the existence of the object. Actually, checking for the existence of a pointer to the object and simply returning if the object does not exist. As an example, here is a common form of initialiser for an object.

- (id)init  {
    // Call the superclass initialiser first and check that it was successful.
    if (!(self = [super init])) {
        // If the superclass initialiser failed then self will be nil.
        // return a nil because we cannot create this object.
        return nil; // Bail!
    }
    // Do more initialising 
    // If we can initialise the superclass and ourself, return a pointer to ourself
    return self;
}

However, the snippets you have provided are not enough to tell whether the code is correct. For example, the first example is incorrect if it is part of an initialiser method because it is not returning any kind of object.

Edit

From your further examples both of these print hiiiiiiii

NSArray *arr;
if(arr) { NSLog(@"hiiiiii");

and

NSArray *arr = [[NSArray alloc]init];
if(arr) { NSLog(@"hiiiiii");

In the first case you are declaring arr to be a pointer to an NSArray, but because it hasn't been initialised this pointer is just a garbage value of random numbers. But it isn't nil So your if-statement evaluates as true. That doesn't mean that it is a valid pointer to an NSArray.

In your second example you declare an NSArray pointer and initialise it. This was successfully initialised so the pointer is not nil and the if-statement evaluates as true. In this case you do have a valid NSArray pointer.

Declaration is not initialisation!

Maybe if you explain what it is that you are trying to do we'll be able to better answer your questions.


They are both checking if the object is nil. In the first case it seems a bit silly though :)


Yes, except in the first case localNotif will not be nil because it has been set

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜