-2

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
thepepp
  • 304
  • 1
  • 3
  • 15
  • 1
    Actually, there is a `new` in Cocoa: http://stackoverflow.com/questions/719877/use-of-alloc-init-instead-of-new-objective-c – Monolo Jan 06 '12 at 03:34

1 Answers1

2

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
}
Ryan Wersal
  • 3,210
  • 1
  • 20
  • 29
  • Or the short-hand form `[MyObject new]`. Also: release it when you're done with it (in this example before the `}`) unless using ARC. –  Jan 05 '12 at 19:08
  • @WTP Both very valid points. I added the `release` just in case anyone not using ARC references this answer. – Ryan Wersal Jan 05 '12 at 20:10