是否可以访问所有者财产的属性?
例如:
@interface Site : NSObject
@property(strong, nonatomic) NSString * siteName;
@property(strong, nonatomic) NSMutableArray * visits;
在创建时,访问数组由n个访问对象填充。每个Visit对象如下所示:
@interface Visit : NSObject
@property(strong, nonatomic) NSDate * visitDate;
@property(assign) int visitStatus;
是否可以在Visit init或类方法中获取Site属性“siteName”。
已实施示例:
Site * site1 = [[Site alloc]init];
site1.siteName = @"SITE NAME";
Visit * siteVisit1 = [[Visit alloc]init];
siteVisit1.visitDate =[NSDate date];
siteVisit1.visitStatus = ongoing;
[site1.visits addObject:siteVisit1];
假设我需要使用网站和日期列表填充UITableView,类似这样但更加格式化。
+-----------+------------+--------------+
| Site Name | Visit Date | Visit Status |
+-----------+------------+--------------+
| Site 1 | 7/8/2014 | planned |
| Site 1 | 8/8/2014 | ongoing |
| Site 1 | 9/8/2014 | ongoing |
| Site 2 | 10/8/2014 | planned |
| Site 2 | 11/8/2014 | ongoing |
| Site 3 | 12/8/2014 | planned |
+-----------+------------+--------------+
可以通过遍历每个站点生成此表,然后为每次访问生成另一个循环。
NSMutableArray * tableViewData = [[NSMutableArray alloc]init];
for (Site * site in siteArray){
for(Visit * visit in site.visits){
[tableViewData addObject:visit];
}
}
在填充UITableView
时,我需要从每个Visit对象访问站点名称Visit * visitForRow = [tableViewData objectAt:indexPath.row];
//Something like this
NSString * siteNameForVisit = [visitForRow getSiteName]; // To have the value "SITE NAME"
cell.siteLabel = siteNameForVisit;
答案 0 :(得分:1)
要实现此功能,您需要在Visit界面中保留Site对象引用。您可以按照以下方式进行操作
\#import "Visit.h"
// Site.h
@interface Site : NSObject
@property(strong, nonatomic) NSString * siteName;
@property(strong, nonatomic) NSMutableArray * visits;
-(Visit*) createVisit;
@end
// Site.m
@imlementation Site
-(Visit*) createVisit{
Visit * siteVisit = [[Visit alloc]initWithSite:self];
return siteVisit;
}
@end
// Visit.h
@interface Visit : NSObject
@property(strong, nonatomic) NSDate * visitDate;
@property(assign) int visitStatus;
-(id)initWithSite:(id)site;
@end
\#import "Site.h"
// Visit.m
@interface Visit : NSObject
@property(weak, nonatomic) Site * site;
@end
@imlementation Visit
-(id)initWithSite:(Site*)site{
self = [super init];
if(self){
_site = site;
}
return self;
}
-(NSString*)getSiteName
{
return self.site.siteName;
}
@end