【问题标题】:How to copy one array to another array which is not in same class in objective c?如何将一个数组复制到目标c中不在同一类中的另一个数组?
【发布时间】:2011-04-14 08:47:26
【问题描述】:

你好
我想将一个数组的元素复制到另一个类中的另一个数组上。
为此,我尝试了各种方法,例如

两个数组不在同一个类中。
例如 secondArray 在 first.h 文件中,数组在 second.h 文件中 然后当我像这样制作 second.h 类的对象时

second *sec; //(in first.h)

并合成它
然后我尝试像这样复制数组 sec=[[第二次分配]init];
sec.array=secondarray;
但是当我在第二类中访问数组时,它显示数组为空

有人对此有任何想法吗?或任何示例代码?

【问题讨论】:

    标签: iphone objective-c copy nsarray


    【解决方案1】:

    尝试按照这些思路做一些事情,我没有看到您的代码,所以这可能不是您问题的确切解决方案,但希望它可以帮助您理解解决问题所需的消息传递。

    //FirstClass .h file
    #import @"SecondClass.h"
    @interface FirstClass : NSObject {
        NSArray         *firstArray; 
        SecondClass     *sec; 
    }
    @property(nonatomic, retain) NSArray        *firstArray; 
    @property(nonatomic, retain) SecondClass    *sec; 
    @end
    
    //Add this to FistClass .m file
    @synthesize firstArray, sec; 
    
    -(id)init{
        if(self == [super init]){
            sec = [[SecondClass alloc] init];
            firstArray = [[NSArray alloc] initWithArray:sec.secondArray];
        }
        return self; 
    }
    
    -(void)dealloc{
        [firstArray release];
        [super dealloc];
    }
    
    //SecondClass .h file
    @interface SecondClass : NSObject {
        NSMutableArray          *secondArray;  
    }
    @property(nonatomic, retain) NSMutableArray     *secondArray; 
    @end
    
    //Add this to SecondClass .m file
    @synthesize secondArray; 
    
    -(id)init{
        if(self == [super init]){
            secondArray = [[NSMutableArray alloc] initWithObjects:@"Obj1", @"Obj2", @"Obj3", nil];//etc... 
            //Maybe add some more objects (this could be in another method?)
            [secondArray addObject:@"AnotherObj"];
    
        }
        return self; 
    }
    
    -(void)dealloc{
        [secondArray release];
        [super dealloc];
    }
    

    【讨论】:

    • 是否有必要在init方法中编写这段代码?因为我已经在secondarray中有来自xml解析的对象
    • 不,只要在 firstClass 内部执行此行之前构造 SecondClass 内部的 secondArray: firstArray = [[NSArray alloc] initWithArray:sec.secondArray];如果你没有这样做,那么 secondArray 将有一个 nil 值,并且不包含要复制到 firstArray 的对象。
    【解决方案2】:

    只是大声说出我脑海中的建议,但请尝试sec.array = secondarray

    【讨论】:

    • 如果您将此帖子标记为问题的解决方案,您可能需要考虑删除您的评论。
    猜你喜欢
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 2022-11-30
    • 2019-12-24
    • 2022-07-05
    • 1970-01-01
    相关资源
    最近更新 更多