开发者

how to use new into for loop

开发者 https://www.devze.com 2023-04-04 20:12 出处:网络
I would like to use new into for loop in objective c for example NSMutablearray *array = [[NSMutableArray alloc]] init];

I would like to use new into for loop in objective c for example

NSMutablearray *array = [[NSMutableArray alloc]] init];

for (int i=0 ; i< 5; i++){
    [array addObject:[[Dire开发者_高级运维ction alloc] initWith:random()];
}

When I run it there is only one object and then stop with messages. but

NSMutablearray *array = [[NSMutableArray alloc]] init];

   Direction * d=  [[Direction alloc] initWith:random()]
   for (int i=0 ; i< 5; i++){
        [array addObject:d];
     [array addObject:d];
     [array addObject:d];
     [array addObject:d];
     [array addObject:d];

    }

there is no error.


NSMutableArray *array = [[[NSMutableArray alloc]] init] autorelease];

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
for (int i=0 ; i< 5; ++i){
    Direction *direction = [[[Direction alloc] initWith:(arc4random()%100)] autorelease];
    [array addObject:direction];
}
[pool drain];


It gives error because your direction object is not released . u are allocing it value evry time loop gose u can do it either two ways

 Direction * d=  [[Direction alloc];

For (loop)
{
d=random() // something like this
}

or

what the above person said u can autorealase it.

0

精彩评论

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

关注公众号