开发者

NSMutableArray adding to self - Convention question

开发者 https://www.devze.com 2023-02-28 00:22 出处:网络
i have a class called Singularity and within it, a method to create a the internals of the object called createSingularity::.

i have a class called Singularity and within it, a method to create a the internals of the object called createSingularity::.

Im wondering, if either of these two methods of adding to self is more appropriate / more efficient.

First method is simply, adding the object to self directly, then to the NSMutableArray. The second method is adding the object to the NSMutableArray, then adding it to self. Check it out:

Method 1 -

    Singularity *asing = [[Singularity alloc]init];
    [sing createSingularity:ccp(150,150) :ccp(2000,150)];
    [self addChild: sing.BlackHoleParticle];
    [_objects addObject: sing];
    [sing release];

Method 2 -

    Singularity *sing = [[Singularity alloc]init];
    [sing createSingularity:ccp(150,150) :ccp(2000,150)];
    [_objects addObject:sing];
    [sing release];
    Singularity *singu = [_objects lastObject];
    [self addChild:singu.whiteHoleParticle];
    [self addChild:singu.blackHoleParticle];
    [singu release];  

Please note t开发者_JAVA技巧hat these objects of Singularity have boundingBoxes and need to be checked via enumeration of the _objects array.

Thank you!


Method 1 is right and Method 2 is wrong.

In Method 2, singu is a reference to an object in the collection and you are releasing the object. You cannot release an object that you dont own. Remove the last line

[singu release]; 

and then it is ok. But there is no point in creating multiple objects to access an element in a function. So stick to method 1

0

精彩评论

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

关注公众号