Katex

顯示具有 Objective-C 標籤的文章。 顯示所有文章
顯示具有 Objective-C 標籤的文章。 顯示所有文章

2012年9月12日 星期三

Mac Day 17 - NSFileManager



NSFileManager 

初始化


有兩種方式:

(1) init 實體方法建立

        NSFileManager *fm = [NSFileManager new];

(2) 使用系統共享的單一物件 (singleton)

        NSFileManager *fm = [NSFileManager defaultManager];

從 Mac OS 10.5 之後建議使用 init 實體方式建立

取得目前所在目錄位置


        NSString *path = [fm currentDirectoryPath];
        NSLog(@"Current directory path is %@", path);

顯示目錄下檔案 (不包括子目錄)


        NSString *path1 = [fm currentDirectoryPath];
        NSDirectoryEnumerator *dirEnum = [fm enumeratorAtPath: path1];
        
        BOOL flag;
        while ((path = [dirEnum nextObject]) != nil) {
            NSLog(@"%@", path);
            
            [fm fileExistsAtPath:path isDirectory: &flag];
            
            if (flag == YES)
                [dirEnum skipDescendants];
        }





2012年9月10日 星期一

Mac Day 15 - Objective C - NSMutableArray

NSMutableArray : 動態陣列




1. [NSMutableArray array]
    [[[NSMutableArray alloc] init] autorelease]



2.  addObject

NSMutableArray *array = [NSMutableArray array];
 [array addObject:@"first"];
 [array addObject:@"second"];

3. 個數
[array count];



2012年9月7日 星期五

MAC Day 12 - Objective C - Class

和 C / C++ 不同地方

1. #import
   是當初 C: #include 的改良版, 保證標頭檔只會被匯入一次
   換言之, 標頭檔 就不用寫成像 :


#ifndef _XXX_H_
#define _XXX_H_
...
#endif

   而可以直接宣告


2.  @autoreleasepool

3.  物件

C++:


obj->method(argument);


Objective C:


[obj method: argument];



[ ClassOrInstance method ];

myDog = [Dog new];
[myDog run];


4. Interface

@interface NewClassName : ParentClassName
    propertyAndMethodDeclarations;
@end



@interface MyObject : NSObject 

+(return_type) class_method;            // 類方法
 
-(return_type) instance_method1;        // 實體方法
-(return_type) instance_method2: (int) p1;
-(return_type) instance_method3: (int) p1 andPar: (int) p2;

@end


+: 類似於 C++ : static function

5. Implementation

@implementation NewClassName
{
    memberDeclarations;
}
    methodDefinitions;
@end



@implementation MyObject
{
    int memberVar1; // 實體變數
    id  memberVar2;
}
+(return_type) class_method { .... //method implementation } -(return_type) instance_method1 { .... } -(return_type) instance_method2: (int) p1 { .... } -(return_type) instance_method3: (int) p1 andPar: (int) p2 { .... } @end


6. NSObject
http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html



7. program



@interface Dog: NSObject
-(void) print;
-(void) setName: (NSString*) name;
@end
@implementation Dog 
{
    NSString *name;
}
-(void) print {
    NSLog(@"%@", name);
}
-(void) setName: (NSString*) n {
    name = n;
}
@end
int main(int argc, const char * argv[])
{      
    @autoreleasepool {
        Dog *myDog;
        NSString *name = @"WonWon";
        
        myDog = [Dog new];
        
        [myDog setName: name];
        
        NSLog(@"My dog's name is");
        [myDog print];
        
    }
    return 0;
}





2012年9月6日 星期四

MAC Day 11 : objective-c : try catch


1. catch


@try {
    ...
}
@catch (CustomException *ce) {   // 1
    ...
}
@catch (NSException *ne) {       // 2
    // Perform processing necessary at this level.
    ...
 
}
@catch (id ue) {
    ...
}
@finally {                       // 3
    // Perform processing necessary whether an exception occurred or not.
    ...
}

2. throw


SException *exception = [NSException exceptionWithName: @"HotTeaException"
                                                 reason: @"The tea is too hot"
                                               userInfo: nil];
@throw exception;

2012年9月5日 星期三

MAC Day 10 - Objective-c - accessor method


1. .h : @property 宣告實體變數

@property(attribute1, attribute2…) type variable

writability :



readonly
-唯讀,只能讀取而不能設定值(不能用setXXXX的函式)。
readwrite-可讀可寫(預設)。


setter semantics


strong - 


f2 = f1;

[f1 retain];
[f2 release];
f2 = f1;

如果沒有將 f2 release, 可能會造成 memory leak
weak - 


避免 retain cycle. 
在 iOS 4 和 OS 10.6 不支援, 須改用 unsafe_unretained


copy-在設值時copy一份新資料,release舊資料。
assign-在設值時替換新舊資料, 而不會增加 retain count(預設)。
retain-在設值時retain新的資料,release舊資料。

Atomicity

nonatomic-預設為atomic以符合多工環境, 設成nonatomic可提高效率


e.g. 
@property double accumulator;



2. .m : @synthesize 存取實體變數

e.g.
@synthesize accumulator;



3. 則不需要額外函式, 就可以存取變數

e.g.
        [myCalc setAccumulator: 100.0];

        NSLog(@"The result is %g", [myCalc accumulator]);





2012年9月4日 星期二

Mac Day 9 - Objective-C - Xcode - Files


依類別存放檔案

1. File -> New -> File


2.  Objective-C class


3.  輸入 class 名稱


4. create 確定後會產生 .m 和 .h 檔




2012年9月3日 星期一

MAC Day 8 - Objective-C - NSString

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html


stringWithString:

Returns a string created by copying the characters from another given string.
+ (id)stringWithString:(NSString *)aString

e.g.     newStr = [NSString stringWithString: oldStr];

UTF8String

Returns a null-terminated UTF8 representation of the receiver.
- (const char *)UTF8String

e.g     NSLog(@"newStr: %s", [newStr UTF8String]);



MAC Day 7 - Objective C - 記憶體管理

1. 自動垃圾回收 Automatic Garbage Collection
2. 手動引用計數 Manual Reference Counting, MRC
3. 自動引用計數 Automatic Reference Counting, ARC

和 Java 很像, Garbage Collection 用 reference counting 來看該塊記憶體有沒有程式使用.
如果沒有就將其透過 release pool 回收.

4. 自動釋放池 Auto release pool
    @autoreleasepool


    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 
    NSLog(@"Hello World!");
 
    [pool drain];


=>


    @autoreleasepool{
        NSLog(@"Hello World!");
    }


5. retain v.s. release
    retain : reference count + 1
    release : reference count -1

2012年9月2日 星期日

MAC Day 6 - Objective C - Hello World

Objective C 是 Brad J. Cox 在 1980 所設計的程式語言, 以 SmallTalk 80 為基礎.
1988 年授權給 NeXT.
1992 年 加入 GNU
1996 年 Apple 將其作為主要的開發語言

Objective C 本身是 C 的延伸語言, 所以原本的 C 程式可以在 Objective-C 上編譯.
以 Xcode 來開發實驗 :

1. Create new project :
     選擇 OS X -> Application, Command Line Tool, 就可以在 MAC 上面執行



2. Options Type : Foundation



3. 進入 IDE 環境後, 修改程式為 C 來試試 :



//#import

#include

int main(int argc, const char * argv[])
{
    
    printf("Hello, World!");

/*
    @autoreleasepool {
        
        // insert code here...
        NSLog(@"Hello, World!");
        
    }
*/
    return 0;
}




原本程式執行結果


改為 C 語言後執行結果


2012年8月30日 星期四

Mac Day 4 : iphone Hello world - Xcode 4.4


iOS : Start Developing iOS Apps


1. Xcode 4.4 : Create a new Xcode project



2. New Project -> Empty Application


3. Product Name : HelloWorld
    Device : iphone
    勾選 :Use Automatic Reference Counting
                 會自動計算參考個數來決定是否回收記憶體

 
4.  專案位置,並有git的版本控管



5. 樣板程式產生了



6. 主程式 :main.m
    int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

  @autoreleasepool : 支援 Auto reference counting

int UIApplicationMain (
   int argc,
   char *argv[],
   NSString *principalClassName,
   NSString *delegateClassName
);
Parameters
argc
The count of arguments in argv; this usually is the corresponding parameter to main.
argv
A variable list of arguments; this usually is the corresponding parameter to main.
principalClassName
The name of the UIApplication class or subclass. If you specify nil, UIApplication is assumed.
delegateClassName
The name of the class from which the application delegate is instantiated. If principalClassName designates a subclass of UIApplication, you may designate the subclass as the delegate; the subclass instance receives the application-delegate messages. Specify nil if you load the delegate object from your application’s main nib file.
Return Value
Even though an integer return type is specified, this function never returns. When users exits an iPhone application by pressing the Home button, the application moves to the background.
7. AppDelegate.m


(1) 點選 icon 啓動 app




(2) 按下 Home 鍵返回桌面時
applicationWillResignActive:
applicationDidEnterBackgroud:
(3) 再由桌面按 icon 返回 app
applicationWillEnterForegroud:
applicationDidBecomeActive:

在 didFinishLaunchingWithOptions 中加入

    UILabel * helloLabel = [[UILabel alloc]init];
    
    helloLabel.frame = CGRectMake(50, 50, 200, 30);

    helloLabel.text= @"Hello World";
    
    [self.window addSubview:helloLabel];


8. 執行程式


完成. 但是這並不是 Model - View - Control 架構. 明天繼續...


熱門文章