我创建了一个带有名称和图像的类。我使用 for 循环来设置 NSMutableArray 和一组对象, 问题是在下一轮将对象添加到数组后,数组将对象设置为空,因为它删除了最后一个对象女巫删除数组中的对象代码
#import "MiMAppDelegate.h"
@interface MiMAnimal : NSObject
@property (nonatomic,weak) NSString *name;
@property (nonatomic,strong) UIImage *image;
- (instancetype) initWithName:(NSString *)name
image:(UIImage *)image;
@end
@implementation MiMAnimal
-(instancetype)initWithName:(NSString *)name image:(UIImage *)image{
self =[super init];
if (self) {
_name = name;
_image = image;
}
return self;
}
- (NSString *)description {
return _name;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
NSMutableArray *Animals = [NSMutableArray array];
for (int i=1; i<30; i++) {
//after the first loop here the array contain 0 the object with null value !!
NSString *name =[[NSString alloc] initWithFormat: @"0%d",i ];
UIImage *image = [UIImage imageNamed:[[NSString alloc] initWithFormat: @"0%d.png",i ]];
NSLog(@"name : %@ ",name);
MiMAnimal *animal =[[MiMAnimal alloc]initWithName:name image:image];
[Animals addObject:animal];
//Here the animals array add the object
}
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
最佳答案
也许它不能解决整个问题,但你应该改变
@property (nonatomic,weak) NSString *name;
到
@property (nonatomic,strong) NSString *name;
因为现在你在离开 for 循环时失去了你的名字。
关于ios - NSMutableArray 在 for 循环中将对象设置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22712584/