2. NSLog(@"some strings"); @"" --> NSString ; "%@"-->是NSString 的佔位符;
3. NSString *getColorName(ShapeColor colorname){return @"red";}
4. @interface Circle : NSObject ; @implementation Circle (實現各個接口中定義的方法)
5. - (void) setColor : (Color) color ; --> void setColor(Color color);
6.[circle setFillColor : red] 函數的調用
7. 接口的定義;
@interface Rectangle : NSObject
{
ShapeColor fillColor;
ShapeRect bounds;
}
- (void) setFillColor: (ShapeColor) fillColor;
- (void) setBounds: (ShapeRect) bounds;
- (void) draw;
@end // Rectangle
8. 實現
@implementation Rectangle
- (void) setFillColor: (ShapeColor) c
{
fillColor = c; //類似於 self-->fillColor = c
} // setFillColor
- (void) setBounds: (ShapeRect) b
{
bounds = b;
} // setBounds
- (void) draw
{
NSLog (@"drawing a rectangle at (%d %d %d %d) in %@",
bounds.x, bounds.y,
bounds.width, bounds.height,
colorName(fillColor));
} // draw
@end // Rectangle
9. [super setColor : red]
10. 組合
@interface Unicycle : NSObject{
Tire *tire;
Pedal * pedal;
}
@end //Unicycle
11. setter and getter
- (Engine *) engine
{
return (engine);
} // engine
- (void) setEngine: (Engine *) newEngine
{
engine = newEngine;
} // setEngine
12. @class Tire 類似於import 但不import更有效率
#import <Cocoa/Cocoa.h>
@class Tire;
@class Engine;
13. 一些有用的數據類型
結構體 :NSRange(location,length) CGPoint(x,y) CGSize(width,height) CGRect(CGPoint,CGSize)
類: NSString
--> + (id) stringWithFormat: (NSString *) format,... ; // + 號代表類方法,也就是靜態方法
NSString *height ;
height = [NSString stringWithFormat : @"height is %d feet, %d inched",5,11];
--> -(NSUInteger) length;
--> -(BOOL) isEqualToString : (NSString *) otherString;
--> -(BOOL) hasPrefix : (NSStirng *) aString;
--> -(BOOL) hasSuffix : (NSStirng *) aString;
--> -(NSRange) rangeOfString (NSStirng *) aString;
--》-(NSString *) pathExtension; //返回文件的擴展名
NSMutableString (繼承於NSString ,相當於Java中的StringBuffer)
--> +(id) stringWithCapacity : (NSUInteger) capacity;
--> -(void) appendString: (NSString *) aString;
--> -(void) appendFormat: (NSString *) aString;
--> -(void) deleteCharactersInRange: (NSRange) aRange;
NSArray (可以存放任意的Objcetive-C的對象) 數組中不能存放nil。
--> +(id) arrayWithObjects : (NSString *) aString,...,nil ;
NSArray arr = [NSArray arrayWithObjects:@"one",@"two",@"three",nil ];
NSArray arr2 = @[@"one",@"two",@"three"];
--> -(NSUInteger) count ;
--> -(id) objectAtIndex:(NSUInteger) index; arr[index]
for(NSInteger i = 0; i < [arr ocunt];i++){
NSLog(@"index %d has %@.",i,arr[i]);
}
NSMutableArray
--> +(id) arrayWithCapacity: (NSUInteger) numItems; //創建可變數組的唯一方式。
--> -(void) addObect: (id) anObject;
--> -(void) removeObjectAtIndex: (NSUInteger) index;
--_ -(void)replaceObjectAtIndex: (NSUInteger) index withObject:(id) object
--> NSEnumerator *enumeraor = [array objectEnumerator];
while(id = thingie = [enumeraor nextObject]){//do sth...}
--> for(NSString *string in array){//do sth...} //快速枚舉
--> [array enumeratorObejctsUsingBlock: (^)(NSStirng *string,NSUInteger index, BOOL *stop){//do sth...}]; //代碼塊 併發迭代
NSDictionary
存
Tire *t1 = [Tire new];Tire *t2 = [Tire new];Tire *t3 = [Tire new];Tire *t4 = [Tire new];
--> NSDictionary *tires = [NSDictionary dictionaryWithObjectsAndKeys: t1,@"front-left",t2,@"front-right",t3,@"back-left",t4,@"back-right",nil];
或者
NSDictionary *tires = @{@"front-left":t1, @"front-right":t2, @"back-left":t3, @"back-right":t4};
取
--> Tire *tire = [tires objectForKey:@"back-right"];
或者
Tire *tire = tires @["back-right"];
NSMutableDictionary
--> +(id) dictionaryWithCapacity : (NSUInteger) numItems ;
--> -(void) setObject:(id) anObject forKey:(id)aKey ;
NSNumber
+(NSNumber *) numberWithChar: (char) value;
+(NSNumber *) numberWithInt: (int) value;
+(NSNumber *) numberWithFloat: (float) value;
+(NSNumber *) numberWithBool: (BOOL) value; //BOOL --> struct
+(NSNumber *) numberWithLong: (long) value;
-(char) charValue, ...
NSValue (NSNumber 的父類)
+(NSValue *)valueWithPoint:(NSPoint)aPoint;
+(NSValue *)valueWithRect:(NSRect)aRect;
+(NSValue *)valueWithSize:(NSSize)aSize;
-(NSPoint) pointValue;
-(NSRect) rectValue;
-(NSSize) sizeValue;
+(NSValue *) valueWithBytes: (const void*) value objCType:(const char *)type;
-(void)getValue:(void*)buffer;
NSRect rect =NSMakeRect(1,2,30,40);
NSValue *value= [NSValue valueWithBytes: &rect objCType:@encode(NSRect)]
[arr addObject:value];
NSNull
+(NSNull *) null; // 這個方法總是返回一樣的值
NSFileManager
+(id) defaultManager;
-(NSDirectoryEnumerator *) enumeratorAtPath:(NSString *) path //home = [@"~" stringByExpandingTildeInPath]; 獲得mac主目錄
14. 內存管理
- (id) retain ; //引用計數+1
- (oneway void) release ; //引用計數-1
- (NSUInteger) retainCount ; //獲取引用計數
- (id) autorelease ; //將對象添加到自動釋放池中
自動釋放池
方式①:
@autoreleasepool{}
方式②:
NSAutoreleasePool *pool;
pool = [[NSAutoreleasePool alloc] init];
...
[pool release];
IOS應用不支持垃圾回收機制 取而代之的是ARC(automatic reference counting)自動引用計數。 在編譯時幫你插入retain 和release語句。
ARC只對可保留的對象指針有效。可保留的對象指針包括
1) 代碼塊指針
2) Objective-C對象指針
3) 通過__attribute__((NSObject)) 類型定義的指針。
強引用 弱引用 歸零弱引用 橋接轉換 好難好難!!!!!
項目 打開或禁用GC Exception ARC
15. 異常
@try
{
}@catch()
{
}@finally
{
}
NSException *e = [NSException exceptionWithName : ...];
@throw e ; //or
[e raise] ;
16 對象初始化
Car *car = [[Car alloc] init] ;
-(id) init;
-(id) initWithFormat: (NSString *) format,...;
-(id) initWithContentsOfFile :(NSString *) path encoding:(NSStringEncoding) enc error: (NSError) error;
[[NSString alloc] initWithContentsOfFile:@"/tep/words.txt" encoding:NSUTF8StringEncoding error:&error]; //第三個參數:沒有錯誤時返回nil
查看錯誤的方法 [error localizedDescription]
%.1f -->一位浮點型
17 @property 屬性
@property float rainHandling; //申明屬性的setter和getter方法 頭文件中
@property float snowHandling;
@synthesize rainHandling; //實現屬性的setter和getter方法 實現文件中 有了這四行話就不用自己申明屬性了
@synthesize snowHandling;
@property (copy) NSString *name; //@property (readonly) NSString *name 只讀屬性
@property (retain) Engine *engine; //可保留指針 使用copy和retain特性, 不保留指針和其他C類型使用assign特性。 默認爲assign和nonatomic
@synthesize name;
@synthesize engien; //使用 car.name=@"somestring" car.engine=[[Engin alloc] init]
@property (readonly) float bodyMassIndex;
@dynamic bodyMassIndex; //告訴編譯器不要創建變量或getter方法。可以自己寫getter方法。
18 類別 category //爲現有的類添加新的方法的方式
@interface NSString (NumberConvenience) //NumberConvenience 是 NSString 的類別。 不可以在類別中添加實例變量,只能添加 @dynamic的屬性
- (NSNumber *)lengthAsNumber;
@end
類擴展
#import <Foundation/Foundation.h>
@interface Things : NSObject
@property (assign) NSInteger thing1;
@property (readonly, assign) NSInteger thing2;
- (void)resetAllValues;
@end
----------------------------
#import "Things.h"
@interface Things ()
{
NSInteger thing4;
}
@property (readwrite, assign) NSInteger thing2;
@property (assign) NSInteger thing3;
@end
@implementation Things
@synthesize thing1;
@synthesize thing2;
@synthesize thing3;
利用類別分散實現代碼
委託類別 *** 委託是一種對象,由另一個類請求執行某些操作
#import <Foundation/Foundation.h>
@interface ITunesFinder : NSObject <NSNetServiceBrowserDelegate>
@end // ITunesFinder
---------------------------------
#import "ITunesFinder.h"
@implementation ITunesFinder
- (void) netServiceBrowser:(NSNetServiceBrowser *) b
didFindService:(NSNetService *) service
moreComing:(BOOL) moreComing
{
[service resolveWithTimeout:10];
NSLog (@"found one! Name is %@", [service name]);
} // didFindService
- (void) netServiceBrowser:(NSNetServiceBrowser *) b
didRemoveService:(NSNetService *) service
moreComing:(BOOL) moreComing
{
[service resolveWithTimeout:10];
NSLog (@"lost one! Name is %@", [service name]);
} // didRemoveService
@end // ITunesFinder
----------------------------------
NSNetServiceBrowser *browser = [[NSNetServiceBrowser alloc] init];
ITunesFinder *finder = [[ITunesFinder alloc] init];
[browser setDelegate: finder];
[browser searchForServicesOfType:@"_daap._tcp"
inDomain:@"local."];
NSLog (@"begun browsing");
[[NSRunLoop currentRunLoop] run]; //run循環 程序將被阻塞到這裏
----------------------------------
非正式協議 : 所有的類都有可能成爲委託對象。 非正式協議是NSObject的一個類別
響應選擇器: NSObject 提供了respondsToSelector:的方法,用以詢問委託對象能都執行某個特定的消息
例如 [car responsToSelector: @selector(setEngien:)]
19. 協議
正式協議 類似於Java中的接口
聲明:
@protocol NSCopying
- (id) copyWithZone: (NSZone *) zone;
@end
繼承
@protocol MyProtocol <NSCopying[,...]>
...
@end
採用協議 (類似於Java裏的實現接口)
@interface Engine : NSObject <NSCopying>
@end // Engine
@implementation Engine
- (id)copyWithZone:(NSZone *)zone
{
Engine *engineCopy = [[[self class] allocWithZone:zone] init];
return (engineCopy);
} // copyWithZone
20. 代碼塊 : 代碼塊本質上是和其他變量類似。不同的是,代碼塊存儲的數據是一個函數體。使用代碼塊是,你可以像調用其他標準函數一樣,傳入參數數,並得到返回值。
語法: int (^myBlock)(int) =^(int num){
return num * 7;
}
example1:
void(^pBlock)(NSString *x);
pBlock = ^(NSString *str){
NSLog(@"print:@",str)
}
pBlock("hello block")
example2:
NSArray *stringArray = [NSArray arrayWithObjects:@"abc 1", @"abc 21", @"abc 12",@"abc 13",@"abc 05",nil];
NSComparator sortBlock = ^(id string1, id string2)
{
return [string1 compare:string2];
};
NSArray *sortArray = [stringArray sortedArrayUsingComparator:sortBlock];
NSLog(@"sortArray:%@", sortArray);
example3: //代碼塊想要遞歸調用,代碼塊變量必須是全局變量或者是靜態變量,這樣在程序啓動的時候代碼塊變量就初始化了,可以遞歸調用
static void (^ const blocks)(int) = ^(int i)
{
if (i > 0) {
NSLog(@"num:%d", i);
blocks(i - 1);
}
};
blocks(3);
example4: //在代碼塊中可以使用和改變全局變量,如果是局部變量,需要加上__block; __block int local = 500;
int global = 1000;
int main(int argc, const char * argv[])
{
@autoreleasepool {
void(^block)(void) = ^(void)
{
global++;
NSLog(@"global:%d", global);
};
block();
NSLog(@"global:%d", global);
}
return 0;
}
21.KVC : KEY-VALUE-CODING 用以獲取類的屬性和一般屬性
#import <Foundation/Foundation.h>
@class Course;
@interface Student : NSObject
{
NSString *name;
Course *course;
NSInteger point;
NSArray *otherStudent;
}
@end
---------------------------------------
#import "Student.h"
#import "Course.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Student *student = [[[Student alloc]init ]autorelease];
[student setValue:@"張三" forKey:@"name"];
NSString *name = [student valueForKey:@"name"];
NSLog(@"學生姓名:%@",name);
[student setValue:@"88" forKey:@"point"];
NSString *point = [student valueForKey:@"point"];
NSLog(@"分數:%@", point);
Student *student1 = [[[Student alloc]init]autorelease];
Student *student2 = [[[Student alloc]init]autorelease];
Student *student3 = [[[Student alloc]init]autorelease];
[student1 setValue:@"65" forKey:@"point"];
[student2 setValue:@"77" forKey:@"point"];
[student3 setValue:@"99" forKey:@"point"];
NSArray *array = [NSArray arrayWithObjects:student1,student2,student3,nil];
[student setValue:array forKey:@"otherStudent"];
NSLog(@"其他學生的成績%@", [student valueForKeyPath:@"otherStudent.point"]);
NSLog(@"共%@個學生", [student valueForKeyPath:@"otherStudent.@count"]);
NSLog(@"最高成績:%@", [student valueForKeyPath:@"[email protected]"]);
NSLog(@"最低成績:%@", [student valueForKeyPath:@"[email protected]"]);
NSLog(@"平均成績:%@", [student valueForKeyPath:@"[email protected]"]);
}
return 0;
}
22.KVO:Key Value Observing
#import <Foundation/Foundation.h>
@interface Student : NSObject
{
NSString *name;
NSString *courseName;
}
-(void)changeCourseName:(NSString*) newCourseName;
@end
----------------------------------------
#import "Student.h"
@implementation Student
-(void)changeCourseName:(NSString*) newCourseName
{
courseName = newCourseName;
}
@end
------------------------------
#import <Foundation/Foundation.h>
@class Student;
@interface PageView : NSObject
{
Student *student;
}
-(id)init:(Student*)initStudent;
@end
-----------------------------------
#import "PageView.h"
#import "Student.h"
@implementation PageView
-(id)init:(Student*)initStudent
{
if (self = [super init]) {
student = initStudent;
[student addObserver:self
forKeyPath:@"courseName"
options:NSKeyValueObservingOptionOld
|NSKeyValueObservingOptionNew context:nil];
}
return self;
}
- (void) dealloc{
[student removeObserver:self forKeyPath:@"courseName" context:nil];
[super dealloc];
}
-(void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if ([keyPath isEqual:@"courseName"]) {
NSLog(@"PageView課程被改變了");
NSLog(@"PageView新課程是:%@ 老課程是:%@", [change objectForKey:@"new"],[change objectForKey:@"old"]);
}
}
@end
------------------------------------------------
#import "Student.h"
#import "Course.h"
#import "PageView.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Student *student = [[[Student alloc]init]autorelease];
[student changeCourseName:@"數學課"];
NSLog(@"初始值:%@", [student valueForKey:@"courseName"]);
//創建頁面實例
PageView *pageview = [[[PageView alloc]init:student]autorelease];
[student setValue:@"化學課" forKey:@"courseName"];
}
return 0;
}
-----------------------------------------------------------------------------
23. Objective-C的選擇器 @selector(),
其作用相當於函數指針,現在我看到的大多說用法都是在調用某些函數需要傳遞一個 函數指針 參數時,使用@selector。它會在當前類裏面查找selector後面所跟的函數,返回一個 SEL類型的值。
SEL變量的執行.用performSelecor方法來執行.
[對象 performSelector:SEL變量 withObject:參數1 withObject:參數2];
在調用respondsToSelector:@selector(method)時,這個method只有在該方法存在參數時需要 ":",如果該方法不需要參數就不需要加這個冒號。否則,編譯不會報錯,只是執行返 回的值不對。當然如果方法有多個參數,需要多個冒號,參數有名稱的需要帶上參數名稱。
如:有如下方法:
-(NSString*)toXmlString;
此時調用類似於:
[self respondsToSelector:@selector(toXmlString)]
如果toXmlString方法的定義爲:
-(NSString*)toXmlString:(NSString*)prefix;
那麼調用就必須加上冒號,如:[self respondsToSelector:@selector(toXmlString:)]
·-(BOOL) isKindOfClass: classObj 用來判斷是否是某個類或其子類的實例
·-(BOOL) isMemberOfClass: classObj 用來判斷是否是某個類的實例
·-(BOOL) respondsToSelector: selector 用來判斷是否有以某個名字命名的方法(被封裝在一個selector的對象裏傳遞)
·+(BOOL) instancesRespondToSelector: selector 用來判斷實例是否有以某個名字命名的方法. 和上面一個不同之處在於, 前面這個方法可以用在實例和類上,而此方法只能用在 類上.
·-(id) performSelector: selector 執行某個方法
@interface foo
-(int)add:int val;
@end
SEL class_func ; //定義一個類方法指針
class_func = @selector(add:int);
注意1. @selector是查找當前類的方法,而[object @selector(方法名:方法參數..) ] ;是取object對應類的相慶方法.
SEL shootSelector = @selector(shoot);
SEL shootAtSelector = @selector(shootAt:);
SEL moveToSelector = @selector(moveTo:withPenColor:);
[obj performSelector:shootSelector]; 無參數的SEL
[obj performSelector:shootAtSelector withObject:coordinate];有一個參數的SEL。
24.
IOS 部分 (內容大部分來自http://blog.csdn.net/totogo2010/這位博主的文章)
Views
-(void)addSubView:(UIView *)aView;
-(void)removeFromSuperview;
通過父view添加子view
通過子view自己移除自己
view的座標系統
單位:
CGFloat ,是個float數字,在obj-c裏就要用這個單位
CGPoint,是個C結構體,CGPoint p = CGPointMake(33.2.22.3); 表示位置。
CGSize, 是個結構體,表示大小。
CGRect :由一個 CGPoint和一個CGSize組成
CGRect labelRect = CGRectMake(20, 20, 50, 30);
UILabel *label = [[UILabel alloc] initWithFrame:labelRect];
label.text = @”Hello!”;
[self.view addSubview:label];
drawRect
怎麼繪圖呢?覆蓋一個方法:-(void)drawRect:(CGRect)aRect;
紅色警告:決不能自己調用drawRect:。系統調用這個方法。如果你需要重繪怎麼辦?發送這兩個消息
view plain copy
- (void)setNeedsDisplay;
- (void)setNeedsDisplayInRect:(CGRect)aRect;
CGContextRef context = UIGraphicsGetCurrentContext();
畫文字
用UILabel
UIFont *myFont = [UIFont systemFontOfSize:12.0];
UIFont *theFont = [UIFont fontWithName:@“Helvetica” size:36.0];
NSArray *availableFonts = [UIFont familyNames];
NSString *text = ...;
[text drawAtPoint:(CGPoint)p withFont:theFont]; // NSString instance method
畫圖像
UIImageView
UIImage *image = [UIImage imageNamed:@“foo.jpg”];
UIImage *image = [[UIImage alloc] initWithContentsOfFile:(NSString *)fullPath];
UIImage *image = [[UIImage alloc] initWithData:(NSData *)imageData];
UIGraphicsBeginImageContext(CGSize);
// draw with CGContext functions
UIImage *myImage = UIGraphicsGetImageFromCurrentContext();
UIGraphicsEndImageContext();
[image drawAtPoint:(CGPoint)p];
[image drawInRect:(CGRect)r];
[image drawAsPatternInRect:(CGRect)patRect;
手勢識別
- (void)setPannableView:(UIView *)pannableView
{
_pannableView = pannableView;
UIPanGestureRecognizer *pangr =
[[UIPanGestureRecognizer alloc] initWithTarget:pannableView action:@selector(pan:)];
[pannableView addGestureRecognizer:pangr];
}
UIPinchGestureRecognizer 縮放
UIRotationGestureRecognizer 旋轉手勢,兩個手指按下,然後旋轉,是個弧度,不是角度。
UISwipeGestureRecognizer 滑動手勢, 一個或多個手指滑動,
UITapGestureRecognizer 點擊手勢
NINetworkImageView 是Nimbus下載圖片的類
plist文件是什麼呢? 它全名是:Property List
<strong>- (void)viewDidLoad
{
[super viewDidLoad];
//讀取plist
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistdemo" ofType:@"plist"];
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
NSLog(@"%@", data);
//添加一項內容
[data setObject:@"add some content" forKey:@"c_key"];
//獲取應用程序沙盒的Documents目錄
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *plistPath1 = [paths objectAtIndex:0];
//得到完整的文件名
NSString *filename=[plistPath1 stringByAppendingPathComponent:@"test.plist"];
//輸入寫入
[data writeToFile:filename atomically:YES];
//那怎麼證明我的數據寫入了呢?讀出來看看
NSMutableDictionary *data1 = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];
NSLog(@"%@", data1);
// Do any additional setup after loading the view, typically from a nib.
}
</strong>
獲取程序的Home目錄
NSString *homeDirectory = NSHomeDirectory
獲取document目錄();
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
獲取Cache目錄
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
獲取Library目錄
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
獲取Tmp目錄
NSString *tmpDir = NSTemporaryDirectory();
寫入文件
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
if (!docDir) {
NSLog(@"Documents 目錄未找到");
}
NSArray *array = [[NSArray alloc] initWithObjects:@"內容",@"content",nil];
NSString *filePath = [docDir stringByAppendingPathComponent:@"testFile.txt"];
[array writeToFile:filePath atomically:YES];
讀取文件
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:@"testFile.txt"];
NSArray *array = [[NSArray alloc]initWithContentsOfFile:filePath];
NSLog(@"%@", array);
在Documents裏創建目錄
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(@"documentsDirectory%@",documentsDirectory);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *testDirectory = [documentsDirectory stringByAppendingPathComponent:@"test"];
// 創建目錄
[fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
在test目錄下創建文件
NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test00.txt"];
NSString *string = @"寫入內容,write String";
[fileManager createFileAtPath:testPath contents:[string dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
獲取目錄列裏所有文件名
兩種方法獲取:NSFileManager 的 subpathsOfDirectoryAtPath 和 subpathsAtPath 方法
fileManager使用操作當前目錄
//創建文件管理器
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//更改到待操作的目錄下
[fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];
//創建文件fileName文件名稱,contents文件的內容,如果開始沒有內容可以設置爲nil,attributes文件的屬性,初始爲nil
NSString * fileName = @"testFileNSFileManager.txt";
NSArray *array = [[NSArray alloc] initWithObjects:@"hello world",@"hello world1", @"hello world2",nil];
[fileManager createFileAtPath:fileName contents:array attributes:nil];
//changeCurrentDirectoryPath目錄更改到當前操作目錄時,做文件讀寫就很方便了,不用加上全路徑
[fileManager removeItemAtPath:fileName error:nil]; //刪除文件
混合數據的讀寫
NSString * fileName = @"testFileNSFileManager.txt";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//獲取文件路徑
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
//待寫入的數據
NSString *temp = @"nihao 世界";
int dataInt = 1234;
float dataFloat = 3.14f;
//創建數據緩衝
NSMutableData *writer = [[NSMutableData alloc] init];
//將字符串添加到緩衝中
[writer appendData:[temp dataUsingEncoding:NSUTF8StringEncoding]];
//將其他數據添加到緩衝中
[writer appendBytes:&dataInt length:sizeof(dataInt)];
[writer appendBytes:&dataFloat length:sizeof(dataFloat)];
//將緩衝的數據寫入到文件中
[writer writeToFile:path atomically:YES];
//讀取數據:
int intData;
float floatData = 0.0;
NSString *stringData;
NSData *reader = [NSData dataWithContentsOfFile:path];
stringData = [[NSString alloc] initWithData:[reader subdataWithRange:NSMakeRange(0, [temp length])]
encoding:NSUTF8StringEncoding];
[reader getBytes:&intData range:NSMakeRange([temp length], sizeof(intData))];
[reader getBytes:&floatData range:NSMakeRange([temp length] + sizeof(intData), sizeof(floatData))];
NSLog(@"stringData:%@ intData:%d floatData:%f", stringData, intData, floatData);
NSBundle介紹和使用
bundle是一個目錄,其中包含了程序會使用到的資源.這些資源包含了如圖像,聲音,編譯好的代碼,nib文件(用戶也會把bundle稱爲plug-in).對應bundle,
cocoa提供了類NSBundle.
// 通過使用下面的方法得到程序的main bundle
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *imagePath = [mainBundle pathForResource:@"QQ20120616-1" ofType:@"png"];
NSLog(@"%@", imagePath);
UIImage *image = [[UIImage alloc]initWithContentsOfFile:imagePath];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[self.view addSubview:imageView];
UINavigationController
UIDatePicker
WebView
UIPickerView
Resource 中的Settings Bundle 打開這個程序的設置
NSThread 有兩種直接創建方式:
- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument
+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument
NSOperation
NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self
selector:@selector(downloadImage:)
object:kURL];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[queue addOperation:operation];
Grand Central Dispatch
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 耗時的操作
dispatch_async(dispatch_get_main_queue(), ^{
// 更新界面
});
});
應用程序的狀態
狀態如下:
Not running 未運行 程序沒啓動
Inactive 未激活 程序在前臺運行,不過沒有接收到事件。在沒有事件處理情況下程序通常停留在這個狀態
Active 激活 程序在前臺運行而且接收到了事件。這也是前臺的一個正常的模式
Backgroud 後臺 程序在後臺而且能執行代碼,大多數程序進入這個狀態後會在在這個狀態上停留一會。時間到之後會進入掛起狀態(Suspended)。有的程序經過特殊的請求後可以長期處於Backgroud狀態
Suspended 掛起 程序在後臺不能執行代碼。系統會自動把程序變成這個狀態而且不會發出通知。當掛起時,程序還是停留在內存中的,當系統內存低時,系統就把掛起的程序清除掉,爲前臺程序提供更多的內存。
各個程序運行狀態時代理的回調:
- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions
告訴代理進程啓動但還沒進入狀態保存
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
告訴代理啓動基本完成程序準備開始運行
- (void)applicationWillResignActive:(UIApplication *)application
當應用程序將要入非活動狀態執行,在此期間,應用程序不接收消息或事件,比如來電話了
- (void)applicationDidBecomeActive:(UIApplication *)application
當應用程序入活動狀態執行,這個剛好跟上面那個方法相反
- (void)applicationDidEnterBackground:(UIApplication *)application
當程序被推送到後臺的時候調用。所以要設置後臺繼續運行,則在這個函數裏面設置即可
- (void)applicationWillEnterForeground:(UIApplication *)application
當程序從後臺將要重新回到前臺時候調用,這個剛好跟上面的那個方法相反。
- (void)applicationWillTerminate:(UIApplication *)application
當程序將要退出是被調用,通常是用來保存數據和一些退出前的清理工作。這個需要要設置UIApplicationExitsOnSuspend的鍵值。
- (void)applicationDidFinishLaunching:(UIApplication*)application
當程序載入後執行
NSDate工廠類方法:
+ (id)dateWithTimeIntervalSinceNow:(NSTimeInterval)secs;
+ (id)dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)secs;
+ (id)dateWithTimeIntervalSince1970:(NSTimeInterval)secs;
NSData提供下面的工廠方法:
+ (id)dataWithBytes:(const void *)bytes length:(unsigned)length;
+ (id)dataWithBytesNoCopy:(void *)bytes length:(unsigned)length;
+ (id)dataWithBytesNoCopy:(void *)bytes length:(unsigned)length
freeWhenDone:(BOOL)b;
+ (id)dataWithContentsOfFile:(NSString *)path;
+ (id)dataWithContentsOfURL:(NSURL *)url;
+ (id)dataWithContentsOfMappedFile:(NSString *)path;
內省是對象自己檢查自己做爲運行時對象詳細信息的一種能力。這些詳細信息包括對象在繼承樹上的位置,對象是否遵循特定的協議,以及是否可以響應特定的消息。NSObject協議和類定義了很多內省方法,用於查詢運行時信息,以便根據對象的特徵進行識別。
實現單例的代碼例子:
static MyGizmoClass *sharedGizmoManager = nil;
+ (MyGizmoClass*)sharedManager
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
[[self alloc] init]; // assignment not done here
}
}
return sharedGizmoManager;
}
+ (id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
sharedGizmoManager = [super allocWithZone:zone];
return sharedGizmoManager; // assignment and return on first allocation
}
}
return nil; //on subsequent allocation attempts return nil
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
ARC技術結合GCD來實現單例模式:
+ (id)sharedInstance
{
static dispatch_once_t pred = 0;
__strong static id _sharedObject = nil;
dispatch_once(&pred, ^{
_sharedObject = [[self alloc] init]; // or some other init method
});
return _sharedObject;
}
動畫
[UIView beginAnimations:@"animation" context:nil];
[UIView setAnimationDuration:1.0f];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:YES];
[UIView commitAnimations];
動畫的常量有以下5種
UIViewAnimationTransitionNone,
UIViewAnimationTransitionFlipFromLeft,
UIViewAnimationTransitionFlipFromRight,
UIViewAnimationTransitionCurlUp,
UIViewAnimationTransitionCurlDown,
交換本視圖控制器中2個view位置
[self.view exchangeSubviewAtIndex:1 withSubviewAtIndex:0];
在commitAnimations消息之前,可以設置動畫完成後的回調,設置方法是:
[UIView setAnimationDidStopSelector:@selector(animationFinish:)];
CALayer
CAAnimation
CAAction 協議。該協議爲圖層觸發一個動畫動作提供了提供標準化響應。
CATransition 提供了一個圖層變化的過渡效果,它能影響圖層的整個內容。 動畫進行的時候淡入淡出(fade)、推(push)、顯露(reveal)圖層的內容。
CAAnimationGroup 允許一系列動畫效果組合在一起,並行顯示動畫。
CAAnimationGroup *animGroup = [CAAnimationGroup animation];
animGroup.animations = [NSArray arrayWithObjects:moveAnim,scaleAnim,opacityAnim, nil];
animGroup.duration = 1;
[view.layer addAnimation:animGroup forKey:nil];
使用手勢很簡單,分爲兩步:
創建手勢實例。當創建手勢時,指定一個回調方法,當手勢開始,改變、或結束時,回調方法被調用。
添加到需要識別的View中。每個手勢只對應一個View,當屏幕觸摸在View的邊界內時,如果手勢和預定的一樣,那就會回調方法。
Macbook SSD硬盤空間不夠用了?來個Xcode大瘦身吧! :
https://mp.weixin.qq.com/s?__biz=MzA5OTU3NjAxNA==&mid=2653645902&idx=1&sn=b880260a997bcaf0dab4a788444d4bbb&scene=0&key=b28b03434249256b7333889a11e33c97056cbf31bb6205da175c1d50f0cf314f26de5cf422b9c6a8cf584f447d9c828c&ascene=0&uin=OTgxODI2NDQw&devicetype=iMac+MacBookPro12%2C1+OSX+OSX+10.11.4+build%2815E65%29&version=11020201&pass_ticket=%2B9iZ5oHULJgM8PEtJyiEiooAxl%2FEDiui7%2FVM4jE5i5LdowfuzDEK1L04O7u4GHws
android
cardview : http://blog.csdn.net/a396901990/article/details/40153759
RTEditor
IOS framework : http://foggry.com/blog/2014/04/25/githubyou-xiu-xiang-mu-ios/