我想知道如何从不同ViewControllers的模型中访问“静态”变量。 我应该去找:
#import "CategoryModel.h"
@implementation CategoryModel
-(NSArray*) allSelected {
return [[NSArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:SELECTEDCATEGORIES_DEFAULTSKEY]];
}
-(NSString*) allSelectedAsUrlParams {
NSMutableString *categoryList = [NSMutableString string];
for (NSArray *category in self.allSelected) {
[categoryList appendString:[category valueForKey:@"value"]];
if(![[self.allSelected lastObject] isEqual:category]) {
[categoryList appendString:@","];
}
}
return categoryList;
}
@end
* 编辑(工作)*
// header
#import <Foundation/Foundation.h>
@interface CategoryModel : NSObject
+ (NSString*)allSelectedAsUrlParams;
@end
// implementation
#import "CategoryModel.h"
@implementation CategoryModel
+ (NSString*)allSelectedAsUrlParams {
return @"somethingGreat";
}
@end
// How to use
CategoryModel.allSelectedAsUrlParams
答案 0 :(得分:1)
这实际上是建筑偏好的问题,但如果不止一个类需要静态变量,这是一种方法:
Constants.h
extern BOOL const TEST_MODE;
extern NSString * const SOME_STRING;
Constants.m
BOOL const TEST_MODE = YES;
NSString * const SOME_STRING = @"SomeString";
作为替代方法,您只需将extern NSString * const SOME_STRING;
添加到特定于其的类的标头(以及.m中对应的NSString * const SOME_STRING = @"SomeString";
),然后通过导入直接调用该var具有您需要的常量的类的标题,并使用SOME_STRING
来获取它。