Objective-C学习笔记和IOS入门

1. main(int argc, char * argv[]){} (因为程序名总是用作启动参数传递,所以argc的值至少是1)

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;  //使用 [email protected]"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:@"[email protected]"]);

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/

时间: 2024-08-07 23:39:43

Objective-C学习笔记和IOS入门的相关文章

iOS学习笔记(八)——iOS网络通信http之NSURLConnection

转自:http://blog.csdn.net/xyz_lmn/article/details/8968182 移动互联网时代,网络通信已是手机终端必不可少的功能.我们的应用中也必不可少的使用了网络通信,增强客户端与服务器交互.这一篇提供了使用NSURLConnection实现http通信的方式. NSURLConnection提供了异步请求.同步请求两种通信方式. 1.异步请求 iOS5.0 SDK NSURLConnection类新增的sendAsynchronousRequest:queu

现代C++学习笔记之二入门篇2,数据转换

static_cast:    这种强制转换只会在编译时检查. 如果编译器检测到您尝试强制转换完全不兼容的类型,则static_cast会返回错误. 您还可以使用它在基类指针和派生类指针之间强制转换,但是,编译器在无法分辨此类转换在运行时是否是安全的. dynamic_cast: dynamic_cast在运行时检查基类指针和派生类指针之间的强制转换. dynamic_cast 是比 static_cast 更安全的强制类型转换,但运行时检查会带来一些开销. const_cast:    con

MySQL学习笔记之一 MySQL入门

本人之前接触的关系型数据库主要是oracle和sqlserver,而对于mysql知之甚少,但查阅网上资料发现,mysql与oracle非常相似,所以学起来应该不会很费劲,在总结的时候可能更多的把关注点放在它与oracle的不同之处. 一.简介 MySQL是一个真正的多用户.多线程SQL数据库服务器.SQL(结构化查询语言)是世界上最流行的和标准化的数据库语言.MySQL是一个客户端/服务器结构的实现, 它由一个服务器守护程序mysqld和很多不同的客户程序和库组成. MySQL的普及并不局限于

现代C++学习笔记之二入门篇1

现代 C++ 强调: 基于堆栈的范围,而非堆或静态全局范围. 自动类型推理,而非显式类型名称. 智能指针而不是原始指针. std::string 和 std::wstring 类型(请参见 <string>),而非原始 char[] 数组. 标准模板库 (STL) 容器(例如 vector.list 和 map),而非原始数组或自定义容器. 请参见 <vector>.<list> 和 <map>. STL 算法,而非手动编码的算法. 异常,可报告和处理错误条

【转】iOS学习笔记(八)——iOS网络通信http之NSURLConnection

移动互联网时代,网络通信已是手机终端必不可少的功能.我们的应用中也必不可少的使用了网络通信,增强客户端与服务器交互.这一篇提供了使用NSURLConnection实现http通信的方式. NSURLConnection提供了异步请求.同步请求两种通信方式. 1.异步请求 iOS5.0 SDK NSURLConnection类新增的sendAsynchronousRequest:queue:completionHandler:方法,从而使iOS5支持两种异步请求方式.我们先从新增类开始. 1)se

spark学习笔记总结-spark入门资料精化

Spark学习笔记 Spark简介 spark 可以很容易和yarn结合,直接调用HDFS.Hbase上面的数据,和hadoop结合.配置很容易. spark发展迅猛,框架比hadoop更加灵活实用.减少了延时处理,提高性能效率实用灵活性.也可以与hadoop切实相互结合. spark核心部分分为RDD.Spark SQL.Spark Streaming.MLlib.GraphX.Spark R等核心组件解决了很多的大数据问题,其完美的框架日受欢迎.其相应的生态环境包括zepplin等可视化方面

iOS学习笔记11-多线程入门

一.iOS多线程 iOS多线程开发有三种方式: NSThread NSOperation GCD iOS在每个进程启动后都会创建一个主线程,更新UI要在主线程上,所以也称为UI线程,是其他线程的父线程. 线程和进程的区别傻傻分不清楚: 线程(thread):用于指代独立执行的代码段. 进程(process):用于指代一个正在运行的可执行程序,它可以包含多个线程. 二.NSThread NSThreadhi轻量级的多线程开发,需要自己管理线程生命周期 创建线程主要实现方法: /* 直接将操作添加到

MyBatis学习笔记(一)入门

一.理解什么是MyBatis? MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架. MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索. MyBatis 可以使用简单的XML 或注解用于配置和原始映射,将接口和 Java 的 POJO( Plain Old Java Objects,普通的Java 对象)映射成数据库中的记录. 1)MyBATIS 目前提供了三种语言实现的版本,包括:Java..NET以及Ruby.(我主要学习java,

jQuery学习笔记之一——jQuery入门与基础核心

因为工作的原因,所以自学了下jQuery,这里以李炎恢老师的教程为自觉教程,并记录学习中遇到的问题. 教程下载地址: http://www.verycd.com/topics/2956408/ 课件下载地址: http://download.csdn.net/download/ip_kv3000/8986013 jQuery类库下载地址: http://jquery.com/ jQuery入门  优势.历史.版本我就不多说了,网上有的是.至于为什么学,因为很有用,为什么非要学他,因为微软加入到了