[英]Objective-C: How to check if 2 properties are the same or not?
假設我有 2 個Person
class 實例。 一個叫約翰,一個叫瑪麗。 Person
class 有 2 個屬性age
和gender
。 有沒有辦法通過所有實例的屬性進行迭代並檢查當前屬性是否等於給定屬性? 像這樣的東西:
for (iterate thorough all properties of instance mary) {
//first iteration
@selector(mary.age)==@selector(john.age) //this would be YES;
//second iteration
@selector(mary.gender)==@selector(john.age) //this would be NO;
}
這個問題解決了如何列出 object 將響應的選擇器:
結合使用 NSObject 協議的-respondsToSelector:
方法,您可以列出 john 的所有選擇器,檢查 mary 是否響應它們,反之亦然。
請參閱打印 object 的所有聲明屬性以迭代並獲取屬性名稱。 您可能需要將它們添加到集合中,然后進行比較。 如果您想檢查類型,它可能會幫助您閱讀 objc 運行時指南中的聲明屬性。
您可以將屬性名稱作為NSStrings
並使用isEqualToString
: 方法來比較它們。
for (iterate thorough all properties of instance mary) {
//first iteration
NSString *marryProperty = [NSString stringWithCString:property_getName(mary.age)
encoding:NSUTF8StringEncoding];
NSString *johnProperty = [NSString stringWithCString:property_getName(john.age)
encoding:NSUTF8StringEncoding];
if([marryProperty isEqualToString:johnProperty])
NSLog(@"YES");
else
NSLog(@"NO");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.