指针混乱

时间:2011-07-04 09:29:20

标签: iphone objective-c ios pointers

我对下面解释的一个指针情况感到困惑;

在A级

@property(nonatomic,retain)NSMutableArray *words;

在B班

 @property(nonatomic,retain)NSMutableArray *words;

 //creating a pointer to words from classB
 self.words = [classB words];

现在,如果我在A类的单词数组中添加新单词,为什么我不在B类的单词数组中看到该单词?我认为B类中的单词数组是指向A类单词的指针?

3 个答案:

答案 0 :(得分:1)

基本上,更改应反映在两个数组中,直到您更改代码中某些位置的任何两个对象的引用

//creating a pointer to words from classB
self.words = [classB words];

A类 B类中的某些地方,

self.words = someOtherArray;

这将使两个类的单词数组指向不同的对象。

答案 1 :(得分:1)

是您尝试运行的代码吗? 如果是,那么B类代码中似乎有一个mystake,因为B类中的单词与[classB words]相同。 (在B类:self.words = [classB words])。 也许像:self.words = [ classA words] ....这样的指令应该解决你的问题(假设classA是A类的对象)。

答案 2 :(得分:1)

正如你们其中一些人所说的,它应该有效,而且确实如此。我的代码中有一些错误。但是想给出一些示例代码来证明它应该是这样的:

#import "PointersAppDelegate.h"

#import "PointersViewController.h"

#import "ClassA.h"
#import "ClassB.h"

@implementation PointersAppDelegate

@synthesize window=_window;

@synthesize viewController=_viewController;

@synthesize classA, classB;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    classA = [[ClassA alloc] init];
    classB = [[ClassB alloc] init];

    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];

    //Add new word to words in classA
    [[classA words] addObject:@"two"];

    //Print words in classB
    [classB print];

    return YES;
}

- (void)dealloc
{
    [_window release];
    [_viewController release];

    [classA release];
    [classB release];

    [super dealloc];
}

@end

// A类

// ClassA.h

@interface ClassA : NSObject {
    NSMutableArray *words;
}
@property(nonatomic,retain)NSMutableArray *words;

@end


// ClassA.m

#import "ClassA.h"

@implementation ClassA

@synthesize words;


- (id)init{
    self = [super init];
    if (self) {
        words = [[NSMutableArray alloc] initWithObjects:@"one", nil];
    }
    return self;
}


- (void)dealloc {
    [words release];
    [super dealloc];
}
@end

ClassB的

// ClassB.h

#import <Foundation/Foundation.h>


@interface ClassB : NSObject {
    NSMutableArray *words;
}
@property(nonatomic,retain)NSMutableArray *words;

-(void)print;

@end


// ClassB.m
#import "ClassB.h"
#import "PointersAppDelegate.h"

@implementation ClassB

@synthesize words;

- (id)init{
    self = [super init];
    if (self) {
        self.words = [[(PointersAppDelegate*)[[UIApplication sharedApplication] delegate] classA] words];
    }
    return self;
}

-(void)print{
    for(int i=0;i<[words count];i++)
        NSLog(@"%@", [words objectAtIndex:i]);
}

- (void)dealloc {
    [words release];

    [super dealloc];
}
@end

结果是:

2011-07-04 12:38:33.759 Pointers[20059:707] one
2011-07-04 12:38:33.767 Pointers[20059:707] two