【问题标题】:Can we use setvalue and forkey attributes for a class object?我们可以为类对象使用 setvalue 和 forkey 属性吗?
【发布时间】:2011-07-22 09:52:00
【问题描述】:

我有一个名为“Book”的类,源代码如下:-

Book.h

#import <"UIKit/UIKit.h>


@interface Book : NSObject {

    NSInteger bookID;
    NSString *title;    //Same name as the Entity Name.
    NSString *author;   //Same name as the Entity Name.
    NSString *summary;  //Same name as the Entity Name.

}

@property (nonatomic, readwrite) NSInteger bookID;

@property (nonatomic, retain) NSString *title;

@property (nonatomic, retain) NSString *author;

@property (nonatomic, retain) NSString *summary;

@end

Book.m

#import "Book.h"

@implementation Book

@synthesize title, author, summary, bookID;

-(void) dealloc {

    [summary release];
    [author release];
    [title release];
    [super dealloc];
}

@end

那么我可以在另一个班级里写:-

Book *aBook = [[Book alloc]init];
[aBook setValue:currentElementValue forKey:elementName];

如果是,那为什么?因为一般在 NSMutableDictionary 中使用 setvalue 和 forkey 来存储数据..

【问题讨论】:

    标签: objective-c ios ios4


    【解决方案1】:

    基本上,键值编码旨在处理对象的属性。 Key-Value Coding Programming Guide 以行开头,

    键值编码是一种间接访问对象属性的机制,使用字符串来标识属性,而不是通过调用访问器方法或通过实例变量直接访问它们。本质上,键值编码定义了应用程序的访问器方法实现的模式和方法签名。

    setObject:forKey:removeObjectForKey: 方法旨在与字典一起使用。您还可以使用 setValue:forKey: 方法将值设置为字典。但是,你不能对类对象使用 setObject:forKey: 方法。

    另一个区别是 setObject:forKey: 不接受 nil 作为值。相反,您应该使用 NSNull 作为值。但是 setValue:forKey: 接受 nil 并从字典中删除键,这样可以节省内存。

    [如果我在某处错了,请有人纠正我!]

    【讨论】:

    • 所以你的意思是我们可以使用 setObject:forKey: 在类对象中存储值... Rigth???
    • 但是我上面写的编码是从网络本身得到的..它工作得很好..书也是一门课。 . aBook 是它的对象,那么它是如何工作的呢??
    • 它的工作,因为你正在使用 setValue:forKey: 方法。如果您使用 setObject:forKey: 方法,它将不起作用;-)