开发者

Understanding properties by writing own setter method

So I'm having trouble with OOAD, properties, the 开发者_StackOverflow中文版self keyword, etc. I wanted to just create a simple test project that has a UITableView. I have an ivar of

NSArray *tableData;

how would I write a setter and getter method for this? I thought my setter would look like:

- (void)setTableData:(NSArray *)array {
    [tableData autorelease];
    tableData = [array retain];
}

Then when I try to use this method in my viewDidLoad, I realize that I need to create an instance of my ViewController. This seems like what not to do when I look at how it's done in books where they create a property for the NSArray, then in viewDidLoad just do a

NSArray *array = [[NSArray alloc] initWithObjects:@"1", @"2", @"3", @"4", nil];
    self.tableData = array;
[array release];

I'm kind of just trying to understand what goes on behind the scenes, to try to understand OOAD principles, ivars, properties, self, etc. Thanks in advance.


I'm sure you already know that using @synthesize will create setter/getter methods for you, but it's good to know what's going on "under the hood" to understand the concepts.

As far as a setter method goes, you're probably better off with something like this:

- (void)setTableData:(NSArray *)array {
    if (tableData != array) {
        [tableData release];
        tableData = [array retain];
    }
}

This basically checks to make sure the new array is actually different than the current. If it is, it releases the old instance and sets the new one.

For a getter method, just use:

- (NSArray *)tableData (
    return tableData;
}

This can be accessed by calling self.tableData. And of course setting the array is done just as you have done, with self.tableData = array;

I hope that helps. If you need more information, just say so and I'll be happy to try and explain further

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜