简体   繁体   English

NSMutableArray添加到自-约定问题

[英]NSMutableArray adding to self - Convention question

i have a class called Singularity and within it, a method to create a the internals of the object called createSingularity::. 我有一个名为Singularity的类,并且在其中有一个创建对象内部的方法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. 第一种方法很简单,直接将对象添加到self,然后添加到NSMutableArray。 The second method is adding the object to the NSMutableArray, then adding it to self. 第二种方法是将对象添加到NSMutableArray,然后将其添加到self。 Check it out: 看看这个:

Method 1 - 方法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 - 方法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 that these objects of Singularity have boundingBoxes and need to be checked via enumeration of the _objects array. 请注意,这些具有奇异性的对象具有boundingBoxes,需要通过_objects数组的枚举进行检查。
Thank you! 谢谢!

Method 1 is right and Method 2 is wrong. 方法1是正确的,方法2是错误的。

In Method 2, singu is a reference to an object in the collection and you are releasing the object. 在方法2中,singu是对集合中对象的引用,而您正在释放该对象。 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 所以坚持方法1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM