函数的调用方式有三种:
第一种:通过self来调用本对象的成员函数
- (IBAction)captureOrderButtonPressed:(UIButton *)sender
{
[self checkUserStateWithSender:sender];
}
第二种:通过类名调用静态全局函数
MBProgressHUD.h
+(void)hudShowWithStatus :(id)viewcontroller : (NSString *)string;//显示1.8消失的提示框
MBProgressHUD.m
+(void)hudShowWithStatus :(id)viewcontroller :(NSString *)string
{
[MBProgressHUD hudShowWithStatus:viewcontroller :string intervl:1.8];
}
调用处:
[MBProgressHUD hudShowWithStatus:self :[error localizedDescription]];
第三种:通过单例对象来调用单例的函数。
API.h
+ (instancetype)shareAPI;
- (void)updateLocationParams:(NSDictionary *)params block:(void(^)(NSError *error))block;//更新地理位置
API.m
- (void)updateLocationParams:(NSDictionary )params block:(void (^)(NSError ))block
{
NSMutableDictionary *muParams = [NSMutableDictionary dictionaryWithDictionary:params];
[muParams setObject:g_updateLocationCmd forKey:@”cmdCode”];
[self GET:@”resetLngLatJsonPhone.htm” params:muParams success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (responseObject) {
FLDDLogDebug(@”success”);
if (block) {
block(nil);
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
FLDDLogInfo(@”error”);
if (block) {
block(error);
}
}];
}
调用:
[[API shareAPI] updateLocationParams:muParams block:^(NSError *error) {
g_updatingLocation = NO;
if (!error) {
FLDDLogDebug(@”updata location success”);
g_loginStat = LOGIN_STATE_LOGIN_SUCESS;
if (self.segmentedControl.selectedSegmentIndex == 0)
{
[self setupRefresh];
}
else
{
[self getOrders];
}
// [self getOrders];
[self showNoticeView];
// [self setupRefresh];
}
else
{
g_loginStat = LOGIN_STATE_UNLOCATION_LOGIN;
}
[self showNoticeView];
}];
+ (instancetype)shareAPI { static API *shareAPI = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ #ifdef DEBUG NSString *baseUrl = [AppManager valueForKey:@"RootUrl"]; if (baseUrl.length == 0) { baseUrl = @"http://test.zuixiandao.cn/fhl/phone/psy/"; [AppManager setUserDefaultsValue:baseUrl key:@"RootUrl"]; } shareAPI = [[API alloc] initWithBaseURL:[NSURL URLWithString:baseUrl]]; #else shareAPI = [[API alloc] initWithBaseURL:[NSURL URLWithString:BaseURL]]; #endif }); shareAPI.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];//设置相应内容类型 shareAPI.securityPolicy.allowInvalidCertificates = NO; [shareAPI.requestSerializer setTimeoutInterval:g_requeRespondTime]; return shareAPI; }
单例又称单子,保证系统的在调用中只生成一个对象,所以若把全局变量存在单例里面就能在通过这个单例访问这些全局变量了。所以IOS的APP几乎都用全局变量,也可以实现部分全局函数代替部分静态全局函数。
通过以下几行代码就能实现单例,简单吧:
+(Singleton *) sharedInstance
{
static Singleton *sharedInstace = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstace = [[self alloc] init]; }); return sharedInstace;
}
若你对C/C++念念不忘也可以用.h文件定义全局变量,在.m文件里包含全局变量头文件就可以,注意在.mm文件里不能用包含全局变量的头文件的方式引用全局变量,需要用extern 声明你需要用到全局变量。一个变量可以有多个声明,只允许一个定义。
extern NSString *g_deviceType;