ios - NSMutableArray 在 for 循环中将对象设置为 null

标签 ios objective-c arrays nsmutablearray

我创建了一个带有名称和图像的类。我使用 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/

相关文章:

ios - -Cocos2D中的[_NSCFConstantString纹理]错误

python - 按元素乘以 1D-numpy 数组(形状(k,1)或(k,))并使结果具有第一个的形状

javascript - 在对象数组中搜索对象

c# - 从 MVC Web 项目发送 Apple 推送通知

ios - UITableViewCell 最小化和最大化动画

html - UIWebView 框架高度基于内容高度

iphone - libxml2.2.dylib 造成大量内存泄漏

iphone - UITextField 选择导致 UITableVIew 拉伸(stretch)

ios - 在 Swift 3 中处理模态视图 Controller 的关闭

java - 尝试使用类型变量创建类的数组时出现 ClassCastException