简体   繁体   English

我们可以为 class object 使用 setvalue 和 forkey 属性吗?

[英]Can we use setvalue and forkey attributes for a class object?

I have a class named "Book" and the source code is as following:-我有一个名为“Book”的 class,源代码如下:-

Book.h书.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书.m

#import "Book.h"

@implementation Book

@synthesize title, author, summary, bookID;

-(void) dealloc {

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

@end

Then within another class can I write:-然后在另一个 class 内我可以写: -

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

If yes then why??如果是那为什么? Because generally setvalue and forkey is used to store data in NSMutableDictionary..因为一般在 NSMutableDictionary 中使用 setvalue 和 forkey 来存储数据..

Basically Key-Value coding is intended to work with an object's properties.基本上,键值编码旨在处理对象的属性。 Key-Value Coding Programming Guide starts with the lines, Key-Value Coding Programming Guide从以下几行开始,

Key-value coding is a mechanism for accessing an object's properties indirectly , using strings to identify properties, rather than through invocation of an accessor method or accessing them directly through instance variables.键值编码是一种间接访问对象属性的机制,使用字符串来标识属性,而不是通过调用访问器方法或通过实例变量直接访问它们。 In essence, key-value coding defines the patterns and method signatures that your application's accessor methods implement.本质上,键值编码定义了应用程序的访问器方法实现的模式和方法签名。

The setObject:forKey: and removeObjectForKey: methods are intended to be used with dictionaries. setObject:forKey:removeObjectForKey:方法旨在与字典一起使用。 You can also use setValue:forKey: method to set values to a dictionary.您还可以使用setValue:forKey:方法将值设置为字典。 But, you can not use setObject:forKey: method for class objects.但是,您不能对 class 对象使用setObject:forKey:方法。

One more difference is that setObject:forKey: doesn't accept nil as the value.另一个区别是setObject:forKey:不接受nil作为值。 Instead you should use NSNull as the value.相反,您应该使用NSNull作为值。 But setValue:forKey: accepts nil and removes the key from the dictionary, which saves the memory.但是setValue:forKey:接受nil并从字典中删除键,从而保存 memory。

[Please someone correct me if I am wrong somewhere!] [如果我在某个地方错了,请有人纠正我!]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM