项目从数组中的数组中消失

时间:2013-08-22 00:20:39

标签: objective-c

我创建了一个我需要的NSMutableArray,只要我的应用程序存在,我就可以在我的主类的@implementation之后调用它suseranArray。该Array将保存一个名为Vassal的类的几个对象。附庸只是:

1)NSMutableString 2)另一个NSMutableString 3)NSMutableArray 4)另一个NSMutable数组

创建的每个Vassal在应用程序的生命周期中也是必需的,它们永远不会改变。

这些对象在.h文件中作为(保留)属性,在.m文件中合成,每当在init函数期间创建对象Vassal时,每个对象都给出一个alloc + init。每个附庸都有数据填写并存储在宗主阵列中。第3个项目总是有几个元素,在出现错误之后,我会设置一条线来检查它是否为空,但它永远不会,生命是好的。

现在,稍后当需要某个Vassal对象时,我们尝试访问其第3个属性来获取那里的数据,有时候该数组为空...我检查它是否以某种方式消失,但它总是在调试中,携带一个很好的地址,如0x2319f8a0,这是有道理的,因为它上面的NSMutableString位于地址0x2319fb40 - (我在经历了很多头痛后期待00000000)。怎么了?我是我的头,我正在创建一个RETAINed对象,它保留默认放入的数据,并且该对象放在另一个对象中,但不知何故,数组内的数据消失了。什么可能的情况可能导致这种情况?谢谢您的时间:))

注意:最后一个数组目前在这个开发阶段只保留一个项目,而且奇怪的是,尽管两个数组是“兄弟”,但是一个项目永远不会丢失

Vassal.h
@interface Vassal : NSObject
@property  (retain) NSMutableString *wordBody;
@property  (retain) NSMutableString *wordCode;
@property   (retain) NSMutableArray *wordRelations;
@property   (retain) NSMutableArray *wordLinks;
@end

Vassal.m
@implementation Vassal:NSObject
@synthesize wordBody;
@synthesize wordCode;
@synthesize wordRelations;
@synthesize wordLinks;
-(NSObject*) init
{
    if(self=[super init])
    {
        wordBody=[[NSMutableString alloc] init];
        wordCode=[[NSMutableString alloc] init];
        wordRelations=[[NSMutableArray alloc] init];
        wordLinks=[[NSMutableArray alloc] init];
    }
    return self;
}

//Somewhere in Suseran:
-(void)fillStuff
{
    ...
    Vassal *vassal=[Vassal new];
    for (int i=0;i<[originalDataString length];i++)
    {
        ...
        [vassal.wordRelations addObject:anItem];
        ...
    }
    int errorTest=[vassal.wordRelations count];
    if (errorTest==0)
    {
         //breakpoint here. Program NEVER comes here
    }
    [bigArrayOfVassals addObject:vassal];
}
//these arrays are never touched again but here:
-(void) getVassalstuff:(NSMutableString*)codeOfDesiredVassal
{
    Vassal *aVassal;
    for (int i=0;i<[bigArrayOfVassals count];i++)
    {
            aVassal=bigArrayOfVassals[i];
            if ([codeOfDesiredVassal isEqualToString:aVassal.wordCode)
            {
                  int errorTest=[aVassal.wordRelations count];
                  if (errorTest==0)
                  {
                         //yay! this breakpoint sometimes is hit, sometimes not,
                         //depending on code's mood. Why is this happening to me? :,(
                  }
            }
    }
}

1 个答案:

答案 0 :(得分:1)

我看到你有可变的属性(除了特定的情况本身是一个坏主意)并且你保留它们。

可变性意味着如果您已根据某些其他数组将数组设置为属性,并且如果更改了原始数组,则属性中的数组也会更改。它可能是,我不知道,因为你没有显示任何代码,你正在清空原始数组,从而改变你作为属性的数组

解决方案:

我首选的解决方案是为您的属性使用这些类的不可变版本; NSString,NSArray而不是保留使用副本

第二个解决方案是将属性保留为可变属性,但为每个属性编写一个自定义setter,用于存储传入的对象的mutableCopy

在这两种情况下,您的属性都是用于设置属性的对象的副本,因此如果在类之外更改对象,则不会影响类的属性。

在评论后编辑添加

如果您将您的财产声明为

@property (copy) NSArray wordRelations;

然后简单地写

vassal wordArray = tempArray;

会做同样的事情,更清洁,更具可读性。

相关问题