在java中,我們經常使用的是單例模式,這些設計模式在ios開發中也比較常用,最近也在考慮使用在ios開發中使用單例模式
在objective-c中,需要在.m文件里面定義個static變量來表示全局變量(和java里面的類變量類似,但是在objective-c中,static變量只是在編譯時候進行初始化,對於static變量,無論是定義在方法體里面 還是在方法體外面其作用域都一樣
在我們經常使用的UITableViewController里面,在定義UITableCellView的時候,模板經常會使用以下代碼
1
2
3
4
5
6
7
8
9
10
11
|
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
return cell;
}
|
在上面 定義了static變量,這個變量在編譯期會對這個變量進行初始化賦值,也就是說這個變量值要么為nil,要么在編譯期就可以確定其值,一般情況下,只能用NSString或者基本類型 ,並且這個變量只能在cellForRowAtIndexPath 訪問,這個變量和java里面的static屬性一樣,但是java的static屬性是可以在java類里面的任何訪問,定義在方法體里面的static變量只能在 對應的訪問里面訪問,但是變量確是類變量。這個和C語言里面的static的變量屬性一樣。
1
2
3
4
5
6
7
8
9
10
11
|
void counter{
static int count = 0;
count ++;
}
counter();
counter();
|
上面代碼執行完成之后,第一次count的值為1,第二次調用count的值為2
static變量也可以定義在.m的方法體外,這樣所有的方法內部都可以訪問這個變量。但是在類之外是沒有辦法方法的,也就是不能用 XXXClass.staticVar 的方式來訪問 staticVar變量。相當於static變量都是私有的。
如果.m文件和方法體里面定義了同名的static 變量,那么方法體里面的實例變量和全局的static變量不會沖突,在方法體內部訪問的static變量和全局的static變量是不同的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
@implementation IFoundAppDelegate
static NSString * staticStr = @"test";
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
static NSString * staticStr = @"test2";
NSLog(@"the staticStr is %@ -- %d",staticStr,[staticStr hash]);
}
- (void)applicationWillResignActive:(UIApplication *)application
{
NSLog(@"the staticStr is %@ -- %d",staticStr,[staticStr hash]);
}
|
以上兩個static變量是兩個不同的變量,在didFinishLaunchingWithOptions方法內部,訪問的是方法體內部定義的staticStr變量,在applicationWillResignActive方法體里面,訪問的全局定義的staticStr變量。可以通過日志打印其 hash來進行確認兩個變量是否一樣。