New and delete command of c++ in obj-c

穿精又带淫゛_ 提交于 2019-12-13 22:37:34

问题


I have an NSMutablearray of objects. the number of objects is set by user. in c++ I would use a for cycle and the 'new' command.something like this:

int fromuser, a;
for(a=0;a<fromuser;a++){
  array addobject:(new class obj) 
}

what do I need to do in obj c since there is no new?


回答1:


You would utilize the alloc and init (or more specialized initializer) provided by NSObject.

For example, something like the following should work:

int fromuser, a;
NSMutableArray objectArray = [[NSMutableArray alloc] initWithCapacity:fromuser];
for (a = 0; a < fromuser; a++)
{
    MyObject *obj = [[MyObject alloc] init];
    [objectArray addObject:obj];
    [obj release]; //If not using ARC
}


来源:https://stackoverflow.com/questions/8748114/new-and-delete-command-of-c-in-obj-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!