开发者

copyWithZone being called

So i have 2 Objects.

Library.h:
   NSString *name;
   Book *book;

Book.h:
   NSString *title
   NSString *author;

The properties are all set up as (readwrite,copy)

ViewController.h:
   Library *library;
   Book *book;

ViewController.m:
   libr开发者_JS百科ary = [[Library alloc] init];
   book = [[Book alloc]init];


  //The fallowing all works
  library.name = @"Library Name";
  book.title = @"book Title";
  book.author = @"book author";

 //The fallowing crashes my app
 library.book = book;

How can I encapsulate Book inside of the library object?

The debugger gives me the fallowing error.

[library copyWithZone:]: unrecognized selector


The -copyWithZone: selector is being called because you're assigning an object to a property that is marked as (copy). Marking it as (copy) tells the compiler to create a setter on your behalf that tries to make a copy of the object being assigned.

You either need to mark your properties as (readwrite, retain), so that you retain the existing instance of Book instead of making a copy, or you need to implement the NSCopying protocol for your Book class. Here's Apple's documentation on NSCopying:

http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Protocols/NSCopying_Protocol/Reference/Reference.html%23//apple_ref/doc/uid/TP40003777

Whether you change the property attributes or adopt the NSCopying protocol depends on whether you truly need to copy the object being assigned (usually only necessary when the object being assigned is modifiable and may be changed by the caller or someone else), or can get away with just retaining a reference to the existing object (considered to be the normal case).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜