首页 >> 大全

Programming in Object C 4th-阅读笔记

2023-09-12 大全 22 作者:考证青年

in C 4th-阅读笔记

由 王宇 原创并发布:

in C 4th 1. 2. in -C and

Table 2.1

// First program example
#import 
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSLog (@"Programming is fun!");
}
return 0;
}

the of

int main (int argc, const char *argv[])
{@autoreleasepool {int value1, value2, sum;value1 = 50;value2 = 25;sum = value1 + value2;NSLog (@"The sum of %i and %i is %i", value1, value2, sum);}return 0;
}

3. , , and What is an ethod() data and

yourCar = [Car new];      // get a new car
[yourCar drive];          // drive your car
[yourCar setSpeed: 55];   // set the speed to 55 mph

call

An -C Class for with

an class in -C

#import 
//---- @interface section ----
@interface Fraction: NSObject
-(void) print;
-(void) setNumerator: (int) n;
-(void) setDenominator: (int) d;
@end
//---- @implementation section ----
@implementation Fraction
{int numerator;int denominator;
}
-(void) print
{NSLog (@"%i/%i", numerator, denominator);
}
-(void) setNumerator: (int) n
{numerator = n;
}
-(void) setDenominator: (int) d
{denominator = d;
}
@end
//---- program section ----
int main (int argc, char * argv[])
{@autoreleasepool {Fraction *myFraction;// Create an instance of a FractionmyFraction = [Fraction alloc];myFraction = [myFraction init];// Set fraction to 1/3[myFraction setNumerator: 1];[myFraction setDenominator: 3];// Display the fraction using the print methodNSLog (@"The value of myFraction is:");[myFraction print];}return 0;
}

The @

-(void)print
+(void)print

The minus sign (-) tells the -C that the is .The only other is a plus sign (+), which a class . A class is one some on the class , such as a new of the class.

(+)可以直接访问,有点类似于,类的 成员

–(int) currentAge;

@implementation NewClassName
{memberDeclarations;
}methodDefinitions;
@end

int main (int argc, char * argv[])
{@autoreleasepool {Fraction *myFraction;// Create an instance of a Fraction and initialize itmyFraction = [Fraction alloc];myFraction = [myFraction init];// Set fraction to 1/3[myFraction setNumerator: 1];[myFraction setDenominator: 3];// Display the fraction using the print methodNSLog (@"The value of myFraction is:");[myFraction print];}return 0;
}

- Fraction *myFraction; is an object of type Fraction(存储实例化对象的内存地址)- myFraction = [Fraction alloc] alloc is short for allocate. You want to allocate memory storage space for a new fraction.- myFraction = [myFraction init] initializes the instance of a class- the two messages are typically conbined:
myFraction = [[Fraction alloc] init];

and Data

You’ve seen how the that deal with can the two and by name. In fact, an can its .A class can’t(不可以直接访问类的成员数据,要通过去实现,比如get set), , it’s only with the class , not with any of the class (think about that for a

).

Now you know how to your own class, or of that class, and send to those .We to the class in later .You’ll learn how to pass to your , how to your class into files, and also how to use key such as and . , now it’s time to learn more about data types and in -C. First, try the that to test your of the in this .

4. Data Types and Data Types and

There are four basic data types:

#import 
int main (int argc, char * argv[])
{@autoreleasepool {int a = 25;int b = 2;float c = 25.0;float d = 2.0;NSLog (@"6 + a / 5 * b = %i", 6 + a / 5 * b);NSLog (@"a / b * b = %i", a / b * b);NSLog (@"c / d * d = %f", c / d * d);NSLog (@"-a = %i", -a);}return 0;
}Program 4.3 Output
6 + a / 5 * b = 16
a / b * b = 24
c / d * d = 25.000000
-a = -25

Program 4.4
// The modulus operator
#import 
int main (int argc, char * argv[])
{@autoreleasepool {int a = 25, b = 5, c = 10, d = 7;NSLog (@"a %% b = %i", a % b);NSLog (@"a %% c = %i", a % c);NSLog (@"a %% d = %i", a % d);NSLog (@"a / d * d + a %% d = %i", a / d * d + a % d);}return 0;
}
Program 4.4 Output
a % b = 0
a % c = 5
a % d = 4
a / d * d + a % d = 25

+= -= /+ 5. 6 7. More on and files

.h // for

.m // for

The first step is to use the@ in your to your

-C and for us by@ in the

Using the Dot

[ ]

.

to

[ setTo: 1 over:3] // setTo is name 'over' is name.

Again, good names is for

Local

- (void) reduce
{int u= numerator;    // local variablesint v= denominator;  // local variablesinttemp;             // local variableswhile(v != 0) {temp= u % v;u= v;v= temp;}numerator/= u;denominator/= u;
}

-(void) calculate: (double) x
{x *= 2;...
}

[ : ptVal];

value was in the ptVal would the local x when the was .

-(int) showPage
{static int pageCount = 0;...++pageCount;...return pageCount;
}

The local would be set to 0 only once when the and would its value of the .

The self

You can use the self to refer to the that is the of the

[self ]

and from

-(Fraction *) add: (Fraction *) f
{
// To add two fractions:
// a/b + c/d = ((a*d) + (b*c)) / (b * d)
// result will store the result of the additionFraction *result = [[Fraction alloc]init];result.numerator = numerator * f.denominator + denominator *f.numerator;result.denominator = denominator * f.denominator;[result reduce];return result;
}resultFraction = [aFraction add: bFraction];

8. It All at the Root

#import 
// ClassA declaration and definition
@interface ClassA: NSObject
{int x;
}
-(void) initVar;
@end
@implementation ClassA
-(void) initVar
{x = 100;
}
@end
// Class B declaration and definition
@interface ClassB : ClassA
-(void) printVar;
@end
@implementation ClassB
-(void) printVar
{NSLog (@"x = %i", x);
}
@end
int main (int argc, char * argv[])
{@autoreleasepool {ClassB *b = [[ClassB alloc] init];[b initVar]; // will use inherited method[b printVar]; // reveal value of x;}return 0;
}

: New

#import “Rectangle.h”
#import "XYPoint.h"
int main (int argc, char * argv[])
{@autoreleasepool{Rectangle *myRect = [[Rectanglealloc]init];XYPoint *myPoint = [[XYPointalloc]init];[myPoint setX: 100andY:200];[myRect setWidth: 5andHeight:8];myRect.origin=myPoint; // 将对象赋值给另外一个对象的成员NSLog (@"Origin at (%i, %i)",myRect.origin.x,myRect.origin.y);[myPoint setX: 50andY:50];NSLog (@"Origin at (%i, %i)",myRect.origin.x,myRect.origin.y);}return0;
}Origin at (100, 200
Origin at (50, 50)-(void) setOrigin: (XYPoint *) pt
{
origin = pt;
}

#import 
// insert definitions for ClassA and ClassB here
int main (int argc, char * argv[])
{@autoreleasepool{ClassA *a = [[ClassAalloc]init];ClassB *b = [[ClassBalloc]init];[a initVar]; // usesClassAmethod[a printVar]; // reveal valueofx;[b initVar]; // use overridingClassBmethod[b printVar]; // reveal valueofx;}return0;
}

: '' may not to '-' // 中没有定义, 此时选择中的

9. , , and Name, Class

// Interface file for Complex class
#import 
@interface Complex: NSObject
@property double real, imaginary;
-(void) print;
-(void) setReal: (double) a andImaginary: (double) b;
-(Complex *) add: (Complex *) f;
@end// Implementation file for Complex class
#import "Complex.h"
@implementation Complex
@synthesize real, imaginary;
-(void) print
{NSLog (@" %g + %gi ", real, imaginary);
}
-(void) setReal: (double) a andImaginary: (double) b
{real = a;imaginary = b;
}
-(Complex *) add: (Complex *) f
{Complex *result = [[Complex alloc] init];result.real = real + f.real;result.imaginary = imaginary + f.imaginary;return result;
}
@end// Shared Method Names: Polymorphism
#import "Fraction.h"
#import "Complex.h"
int main (int argc, char * argv[])
{@autoreleasepool {Fraction *f1 = [[Fraction alloc] init];Fraction *f2 = [[Fraction alloc] init];Fraction *fracResult;Complex *c1 = [[Complex alloc] init];Complex *c2 = [[Complex alloc] init];Complex *compResult;[f1 setTo: 1 over: 10];[f2 setTo: 2 over: 15];[c1 setReal: 18.0 andImaginary: 2.5];[c2 setReal: -5.0 andImaginary: 3.2];// add and print 2 complex numbers[c1 print]; NSLog (@" +"); [c2 print];NSLog (@"---------");compResult = [c1 add: c2]; // 多态[compResult print];NSLog (@"\n");// add and print 2 fractions[f1 print]; NSLog (@" +"); [f2 print];NSLog (@"----");fracResult = [f1 add: f2]; // 多态[fracResult print];}return 0;
}

and the id Type

#import "Fraction.h"
#import "Complex.h"
int main (int argc, char * argv[])
{@autoreleasepool {id dataValue;Fraction *f1 = [[Fraction alloc] init];Complex *c1 = [[Complex alloc] init];[f1 setTo: 2 over: 5];[c1 setReal: 10.0 andImaginary: 2.5];// first dataValue gets a fractiondataValue = f1;  // id Type[dataValue print];// now dataValue gets a complex numberdataValue = c1;[dataValue print];}return 0;
}

Time

id变量中的对象类型在编译时无法确定,所以一些测试推迟到运行时运行

The id Data Type and

不可以把所有的对象都声明为id类型:

About

One you to ask an to a (see 11,“ and ”). you to

ask about (not in this text).

[ clase] // 返回类的名字

@

Using @try

@try {statementstatement
...
}
@catch (NSException *exception) {statementstatement
...
}

10. More on and Data Types

Fraction *myFract = [[Fraction alloc] init];

- (id)init  // 注意这个返回类型
{self = [super init];  // 执行父类的初始化if (self) {// Initialization code here.}return self;
}

Scope

@interface Printer
{
@privateint pageCount;int tonerLevel;
@protected// other instance variables
}
...
@end

@ =;

it says to the and for the named and to that with an (which does not have to be ).This helps to the use of the from the and to you to set and the value of the the and .That is, like this

[ ]; // This won't work

will fail, as there is no named . , you have to name the by its name, such as

[ ];

or, , use the :

[self. ]

#import "Foo.h"int gGlobalVar = 5;  // this is global variablesint main (int argc, char *argc[])
{@autoreleasepool {Foo *myFoo = [[Foo alloc] init];NSLog (@"%i ", gGlobalVar);[myFoo setgGlobalVar: 100];NSLog (@"%i", gGlobalVar);}return 0;
}

The of the in the makes its value by any (or ) that uses an . your Foo : looks like this:

-(void) setgGlobalVar: (int) val
{extern int gGlobalVar;  // 引用全局变量gGlobalVar = val;}  

定义全局的,但不是外部的

in = 0;

以上声明在任何方法函数之外,那么在该文件中,所有位于这条语句之后的方法或函数都可以访问的值, 而其他文件中的方法和函数不行

Data Types

enum flag { false, true };

#import // print the number of days in a month
int main (int argc, char * argv[])
{@autoreleasepool {enum month { january = 1, february, march, april, may, june, july, august, september, october, november, december };enum month amonth; // 枚举int days;NSLog (@"Enter month number: ");scanf ("%i", &amonth);switch (amonth) {case january:case march:case may:case july:case august:case october:case december:days = 31;break;case april:case june:case september:case november:days = 30;break;case february:days = 28;break;default:NSLog (@"bad month number");days = 0;break;}if ( days != 0 )NSLog (@"Number of days is %i", days);if ( amonth == february )NSLog (@"...or 29 if it's a leap year");}return 0;
}

The

// 1
typedef int Counter;
Counter j, n;// 2
typedef NSNumber *NumberObject;
NSNumber *myValue1, *myValue2, *myResult;// 3
typedef enum { east, west, south, north } Direction;
Direction step1, step2;

Data Type

Rules

Bit

& AND

| -OR

^ OR

~ Ones

> Right shift

11. and

A an easy way for you to the of a class into or of . gives you an easy way to an class even to the code for the class and to a .This is a yet easy for you to learn.

#import "Fraction.h"  // 必须包含原始接口部分
@interface Fraction (MathOps) // This tells the compiler that you // are defining a new category for the // Fraction class// and that its name is MathOps.
-(Fraction *) add: (Fraction *) f;
-(Fraction *) mul: (Fraction *) f;
-(Fraction *) sub: (Fraction *) f;
-(Fraction *) div: (Fraction *) f;
@end@implementation Fraction (MathOps) // 
-(Fraction *) add: (Fraction *) f
{// To add two fractions:// a/b + c/d = ((a*d) + (b*c)) / (b * d)Fraction *result = [[Fraction alloc] init];result.numerator = (self.numerator * f.denominator) +(self.denominator * f.numerator);result.denominator = self.denominator * f.denominator;[result reduce];return result;
}
-(Fraction *) sub: (Fraction *) f
{// To sub two fractions:// a/b - c/d = ((a*d) - (b*c)) / (b * d)Fraction *result = [[Fraction alloc] init];result.numerator = (self.numerator * f.denominator) -(self.denominator * f.numerator);result.denominator = self.denominator * f.denominator;[result reduce];return result;
}
-(Fraction *) mul: (Fraction *) f
{Fraction *result = [[Fraction alloc] init];result.numerator = self.numerator * f.numerator;result.denominator = self.denominator * f.denominator;[result reduce];return result;
}
-(Fraction *) div: (Fraction *) f
{Fraction *result = [[Fraction alloc] init];result.numerator = self.numerator * f.denominatorresult.denominator = self.denominator * f.numerator;[result reduce];return result;
}
@end
int main (int argc, char * argv[])
{@autoreleasepool {Fraction *a = [[Fraction alloc] init];Fraction *b = [[Fraction alloc] init];Fraction *result;[a setTo: 1 over: 3];[b setTo: 2 over: 5];[a print]; NSLog (@" +"); [b print]; NSLog (@"-----");result = [a add: b];[result print];NSLog (@"\n");[a print]; NSLog (@" -"); [b print]; NSLog (@"-----");result = [a sub: b];[result print];NSLog (@"\n");[a print]; NSLog (@" *"); [b print]; NSLog (@"-----");result = [a mul: b];[result print];NSLog (@"\n");[a print]; NSLog (@" /"); [b print]; NSLog (@"-----");result = [a div: b];[result print];NSLog (@"\n");}return 0;
}

Note

By , the base name of the .h and .m files for a is the class name by the name. In our , we would put the for the in a file named .h and the in a file

.m. Some use a ‘+’ sign to the name of the from the class, as in +.h.

Class

There is a case of a a name, that is no name is

the ( and ) .This what is known as a class .

#import "GraphicObject.h"
// Class extension
@interface GraphicObject () // 注意这里的(), 为class extension 或理解为 Categories without name
@property int uniqueID;
-(void) doStuffWithUniqueID: (int) theID;
@end//--------------------------------------
@implementation GraphicObject
@synthesize uniqueID;-(void) doStuffWithUniqueID: (int) myID
{self.uniqueID = myID;
...
}
...
// Other GraphicObject methods
...
@end

@protocol NSCopying
- (id)copyWithZone: (NSZone *)zone;
@end

@interface AddressBook: NSObject This says that AddressBook is an object whose parent is NSObject and states that it conforms to the NSCopying protocol. 

if ([currentObject conformsToProtocol: @protocol (Drawing)] == YES)
{
// Send currentObject paint, erase and/or outline msgs
...
}id  currentObject;

@protocol Drawing3D 

@

@

本身应该称为一种设计模式,是把一个类自己需要做的一部分事情,让另一个类(也可以就是自己本身)来完成,而实际做事的类为。而是一种语法,它的主要目标是提供接口给遵守协议的类使用,而这种方式提供了一个很方便的、实现模式的机会。

参考:

1,先定义一个协议() , 协议中定义了两个方法: first ,

2,现在这里定义两个类和来实现协议中的方法.

3,然后新建一个 C类,但是这个类并没有去遵循协议 去实现其他的方法,而是通过委托来代理实现协议方法的调用。

#import 
#import "ProtocolName.h"@interface Student : NSObject{id delegate; // 委托
}@property (retain) id delegate; // 将委托设置为一个属性-(void) setMethod;@end// 使用委托
Student *stu=[[Student alloc] init];StudentA *stua=[[StudentA alloc] init];StudentB *stub=[[StudentB alloc] init];stu.delegate=stua;[stu.delegate first];[stu setMethod];stu.delegate=stub;[stu setMethod];

@interface Square: NSObject
{Rectangle *rect; // 合成对象,而不是继承对象
}
-(int) setSide: (int) s;
-(int) side;
-(int) area;
-(int) perimeter;
@end

12. The The # The # 13. C

int integers[5] = { 0, 1, 2, 3, 4 } ;
char letters[5] = { 'a', 'b', 'c', 'd', 'e' } ;

char word[] = { 'H', 'e', 'l', 'l', 'o', '!' } ;

int M[4][7] = {
{ 10, 5, -3, 17, 82 } ,
{ 9, 0, 0, 8, -7 } ,
{ 32, 20, 1, 0, 14 } ,
{ 0, 0, 8, 7, 6 }
} ;

#import // Function to calculate the nth triangular number
void calculateTriangularNumber (int n)
{int i, triangularNumber = 0;for ( i = 1; i <= n; ++i )triangularNumber += i;NSLog (@"Triangular number %i is %i", n, triangularNumber);
}int main (int argc, char * argv[])
{
@autoreleasepool {calculateTriangularNumber (10);calculateTriangularNumber (20);calculateTriangularNumber (50);
}
return 0;
}

int gcd (int u, int v)
{return u * v;
}
result = gcd (150, 35);

块从本质上来说是一个闭包,即其拥有代码逻辑和运行该段代码逻辑需要的变量。这一切在定义代码时就已经确定,因此,一个块在定义时访问了某个上文变量,即使之后该上下文变量发生了变化,块中仍然使用是定义时的值,可以认为块只是在定义的时候拷贝了一个变量值到自己的作用域。定义完之后,和原来的那个上下文变量就没有关系了。

void printMessage (void)
{NSLog (@"Programming is fun.");
}^(void)
{NSLog (@"Programming is fun.");
}void (^printMessage)(void) =
^(void){NSLog (@"Programming is fun.");
} ;

struct date
{int month;int day;int year;
} ;struct date today;

struct date today = { 7, 2, 2011 } ;struct date today = { .month = 7, .day = 2, .year = 2011 } ;

/* Points. */
struct CGPoint {CGFloat x;CGFloat y;
} ;typedef struct CGPoint CGPoint;/* Sizes. */
struct CGSize {CGFloat width;CGFloat height;
} ;typedef struct CGSize CGSize;

struct date
{int month;int day;int year;
} todaysDate, purchaseDate;struct date
{int month;int day;int year;
} todaysDate = { 9, 25, 2011 } ;struct
{int month;int day;int year;
} dates[100];

To the way , you first must the

(&)and (*).

struct date
{
int month;
int day;
int year;
} ;struct date todaysDate;
struct date *datePtr;datePtr = &todaysDate;

#import 
int arraySum (int array[], int n)
{int sum = 0, *ptr;int *arrayEnd = array + n;for ( ptr = array; ptr < arrayEnd; ++ptr )sum += *ptr;return (sum);
}
int main (int argc, char * argv[])
{@autoreleasepool {int arraySum (int array[], int n);int values[10] = { 3, 7, -9, 3, 6, -1, 7, 9, 1, -5 } ;NSLog (@"The sum is %i", arraySum (values, 10));}return 0;
}

for ( ; *from != '\ 0'; )  // 指针定义以后,使用时为什么还要用*号
*to++ = *from++;

int (*fnPtr) (void);

They're Not ! How Work 14 to the

Quick for

15. , , and

#import 

#import 
int main (int argc, char * argv[])
{@autoreleasepool {NSNumber *myNumber, *floatNumber, *intNumber;NSInteger myInt;// integer valueintNumber = [NSNumber numberWithInteger: 100];myInt = [intNumber integerValue];NSLog (@"%li", (long) myInt);// long valuemyNumber = [NSNumber numberWithLong: 0xabcdef];NSLog (@"%lx", [myNumber longValue]);// char valuemyNumber = [NSNumber numberWithChar: 'X'];NSLog (@"%c", [myNumber charValue]);// float valuefloatNumber = [NSNumber numberWithFloat: 100.00];NSLog (@"%g", [floatNumber floatValue]);// doublemyNumber = [NSNumber numberWithDouble: 12345e+15];NSLog (@"%lg", [myNumber doubleValue]);// Wrong access hereNSLog (@"%li", (long) [myNumber integerValue]);// Test two Numbers for equalityif ([intNumber isEqualToNumber: floatNumber] == YES)NSLog (@"Numbers are equal");elseNSLog (@"Numbers are not equal");// Test if one Number is <, ==, or > second Numberif ([intNumber compare: myNumber] == NSOrderedAscending)NSLog (@"First number is less than second");}return 0;
}

Note: Table 15.1 and

int main (int argc, char * argv[])
{@autoreleasepool {NSString *str = @"Programming is fun";NSLog (@"%@", str);}return 0;
}

-(NSString *) description
{return [NSString stringWithFormat: @"%i/%i", numerator, denominator];
}

#import 
int main (int argc, char * argv[])
{@autoreleasepool {NSString *str1 = @"This is string A";NSString *search, *replace;NSMutableString *mstr;NSRange substr;// Create mutable string from nonmutablemstr = [NSMutableString stringWithString: str1];NSLog (@"%@", mstr);// Insert characters[mstr insertString: @" mutable" atIndex: 7];NSLog (@"%@", mstr);// Effective concatentation if insert at end[mstr insertString: @" and string B" atIndex: [mstr length]];NSLog (@"%@", mstr);// Or can use appendString directly[mstr appendString: @" and string C"];NSLog (@"%@", mstr);// Delete substring based on range[mstr deleteCharactersInRange: NSMakeRange (16, 13)];NSLog (@"%@", mstr);// Find range first and then use it for deletionsubstr = [mstr rangeOfString: @"string B and “];if (substr.location != NSNotFound) {[mstr deleteCharactersInRange: substr];NSLog (@"%@", mstr);}// Set the mutable string directly[mstr setString: @"This is string A"];NSLog (@"%@", mstr);// Now let’s replace a range of chars with another[mstr replaceCharactersInRange: NSMakeRange(8, 8)withString: @"a mutable string"];NSLog (@"%@", mstr);// Search and replacesearch = @"This is";replace = @"An example of";substr = [mstr rangeOfString: search];if (substr.location != NSNotFound) {[mstr replaceCharactersInRange: substrwithString: replace];NSLog (@"%@", mstr);}// Search and replace all occurrencessearch = @"a";replace = @"X";substr = [mstr rangeOfString: search];while (substr.location != NSNotFound) {[mstr replaceCharactersInRange: substrwithString: replace];substr = [mstr rangeOfString: search];}NSLog (@"%@", mstr);}return 0;
}

Array

are by the class, ones are by .

#import 
int main (int argc, char * argv[])
{int i;@autoreleasepool {// Create an array to contain the month namesNSArray *monthNames = [NSArray arrayWithObjects:@"January", @"February", @"March", @"April",@"May", @"June", @"July", @"August", @"September",@"October", @"November", @"December", nil ];// Now list all the elements in the arrayNSLog (@"Month Name");NSLog (@"===== ====");for (i = 0; i < 12; ++i)NSLog (@" %2i %@", i + 1, [monthNames objectAtIndex: i]);}return 0;
}

A is a of data of key- pairs

int main (int argc, char * argv[])
{@autoreleasepool {NSMutableDictionary *glossary = [NSMutableDictionary dictionary];// Store three entries in the glossary[glossary setObject: @"A class defined so other classes can inherit from it"forKey: @"abstract class" ];[glossary setObject: @"To implement all the methods defined in a protocol"forKey: @"adopt"];[glossary setObject: @"Storing an object for later use"forKey: @"archiving"];// Retrieve and display themNSLog (@"abstract class: %@", [glossary objectForKey: @"abstract class"]);NSLog (@"adopt: %@", [glossary objectForKey: @"adopt"]);NSLog (@"archiving: %@", [glossary objectForKey: @"archiving"]);}return 0;
}

#import 
int main (int argc, char * argv[])
{@autoreleasepool {NSDictionary *glossary =[NSDictionary dictionaryWithObjectsAndKeys:@"A class defined so other classes can inherit from it",@"abstract class",@"To implement all the methods defined in a protocol",@"adopt",@"Storing an object for later use",@"archiving",nil];// Print all key-value pairs from the dictionaryfor ( NSString *key in glossary )NSLog (@"%@: %@", key, [glossary objectForKey: key]);}return 0;
}

Set

A set is , and it can be or .

#import // Create an integer object
#define INTOBJ(v) [NSNumber numberWithInteger: v]
// Add a print method to NSSet with the Printing category
@interface NSSet (Printing)
-(void) print;
@end@implementation NSSet (Printing)
-(void) print {
printf ("{ ");
for (NSNumber *element in self)
printf (" %li ", (long) [element integerValue]);
printf ("} \n");
}
@endint main (int argc, char * argv[])
{@autoreleasepool {NSMutableSet *set1 = [NSMutableSet setWithObjects:INTOBJ(1), INTOBJ(3), INTOBJ(5), INTOBJ(10), nil];NSSet *set2 = [NSSet setWithObjects:INTOBJ(-5), INTOBJ(100), INTOBJ(3), INTOBJ(5), nil];NSSet *set3 = [NSSet setWithObjects:INTOBJ(12), INTOBJ(200), INTOBJ(3), nil];NSLog (@"set1: ");[set1 print];NSLog (@"set2: ");[set2 print];// Equality testif ([set1 isEqualToSet: set2] == YES)NSLog (@"set1 equals set2");elseNSLog (@"set1 is not equal to set2");// Membership testif ([set1 containsObject: INTOBJ(10)] == YES)NSLog (@"set1 contains 10");elseNSLog (@"set1 does not contain 10");if ([set2 containsObject: INTOBJ(10)] == YES)NSLog (@"set2 contains 10");elseNSLog (@"set2 does not contain 10");// add and remove objects from mutable set set1[set1 addObject: INTOBJ(4)];[set1 removeObject: INTOBJ(10)];NSLog (@"set1 after adding 4 and removing 10: ");[set1 print];// get intersection of two sets[set1 intersectSet: set2];NSLog (@"set1 intersect set2: ");[set1 print];// union of two sets[set1 unionSet:set3];NSLog (@"set1 union set3: ");[set1 print];}return 0;
}

16. with Files Files and :

A file or is a to the file.A is an that can be a or full .A is one that is to the .

The tilde (~) is used as an for a user’s home .

#import 
int main (int argc, const char * argv[]) {@autoreleasepool {NSString *fName = @"testfile";NSFileManager *fm;NSDictionary *attr;// Need to create an instance of the file managerfm = [NSFileManager defaultManager];// Let's make sure our test file exists firstif ([fm fileExistsAtPath: fName] == NO) {NSLog(@"File doesn't exist!");return 1;}//now lets make a copyif ([fm copyItemAtPath: fName toPath: @"newfile" error: NULL] == NO) {NSLog(@"File Copy failed!");return 2;}// Now let's test to see if the two files are equalif ([fm contentsEqualAtPath: fName andPath: @"newfile"] == NO) {NSLog(@"Files are Not Equal!");return 3;}// Now lets rename the copyif ([fm moveItemAtPath: @"newfile" toPath: @"newfile2"error: NULL] == NO){NSLog(@"File rename Failed");return 4;}// get the size of the newfile2if ((attr = [fm attributesOfItemAtPath: @"newfile2" error: NULL])== nil) {NSLog(@"Couldn't get file attributes!");return 5;}NSLog(@"File size is %llu bytes",[[attr objectForKey: NSFileSize] unsignedLongLongValue]);// And finally, let's delete the original fileif ([fm removeItemAtPath: fName error: NULL] == NO) {NSLog(@"file removal failed");return 6;}NSLog(@"All operations were successful");// Display the contents of the newly-created fileNSLog(@"%@", [NSString stringWithContentsOfFile:@"newfile2" encoding:NSUTF8StringEncoding error:NULL]);}return 0;
}

#import 
int main (int argc, char * argv[])
{@autoreleasepool {NSFileManager *fm;NSData *fileData;fm = [NSFileManager defaultManager];// Read the file newfile2fileData = [fm contentsAtPath: @"newfile2"];if (fileData == nil) {NSLog (@"File read failed!");return 1;}// Write the data to newfile3if ([fm createFileAtPath: @"newfile3" contents: fileDataattributes: nil] == NO) {NSLog (@"Couldn't create the copy!");return 2;}NSLog (@"File copy was successful!");}return 0;
}

#import 
int main (int argc, char * argv[])
{@autoreleasepool {NSString *dirName = @"testdir";NSString *path;NSFileManager *fm;// Need to create an instance of the file managerfm = [NSFileManager defaultManager];// Get current directorypath = [fm currentDirectoryPath];NSLog (@"Current directory path is %@", path);// Create a new directoryif ([fm createDirectoryAtPath: dirName withIntermediateDirectories: YESattributes: nil error: NULL] == NO) {NSLog (@"Couldn't create directory!");return 1;}// Rename the new directoryif ([fm moveItemAtPath: dirName toPath: @"newdir" error: NULL] == NO) {NSLog (@"Directory rename failed!");return 2;}// Change directory into the new directoryif ([fm changeCurrentDirectoryPath: @"newdir"] == NO) {NSLog (@"Change directory failed!");return 3;}// Now get and display current working directorypath = [fm currentDirectoryPath];NSLog (@"Current directory path is %@", path);NSLog (@"All operations were successful!");}return 0;
}

#import 
int main (int argc, char * argv[])
{@autoreleasepool {NSString *path;NSFileManager *fm;NSDirectoryEnumerator *dirEnum;NSArray *dirArray;// Need to create an instance of the file managerfm = [NSFileManager defaultManager];// Get current working directory pathpath = [fm currentDirectoryPath];// Enumerate the directorydirEnum = [fm enumeratorAtPath: path];NSLog (@"Contents of %@", path);while ((path = [dirEnum nextObject]) != nil)NSLog (@"%@", path);// Another way to enumerate a directorydirArray = [fm contentsOfDirectoryAtPath:[fm currentDirectoryPath] error: NULL];NSLog (@"Contents using contentsOfDirectoryAtPath:error:");for ( path in dirArray )NSLog (@"%@", path);}return 0;
}

with Paths: .h Basic File : The NSURL Class The Class 17. and

The iOS doesn’t , so you don’t have the to use it when for that .That is, you can only use it when Mac OS X .

(ARC)

The is as :When an is , its count is set to 1. Each time you need to that the be kept , you a to it by its count by 1.This is done by the a , like so:

[ ];

When you no need an , you its count by 1 by it a , like this:

[ ];

When the count of an 0, the knows that the is no being used (, in , it is no being in the ), so it frees up () its .

[ ];

When with that use from the , UIKit, or , you must an pool from these can and .You do that in your with a like this:

* pool = [[ alloc] init];

Xcode a file with this at the start of main if you a new ARC . As noted, after the pool is set up, add new such as , , , views, , and other to the list by the pool.

When you’re done using the pool, you send it a drain :

[pool drain];

The Event Loop and

当一次Event Loop 发生时,系统会偏离 pool 中 auto 数组,并且释放资源

of Rules (ARC) Stong

By , all are .That means that an to such a that to be

Week

To a weak you use the _ _weak :

_ _weak *;

or you use the weak for a :

@ (weak, ) *;

@

@autoreleasepool {}
替换
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];[pool drain];

Names and Non-ARC Code 18. The copy and

The known as copy and that you can use to a copy of an .This is done by a in with for . If your class needs to and of an , you must a to as well.You learn how to do that later in this .

= [ ];

这个例子中,数组中放的是字符串

Deep

// Shallow copy, 仅仅复制了数组的地址,没有复制数组中的元素
dataArray2 = [dataArray mutableCopy];

这个例子中,数组中放的是指针

浅复制,仅仅复制地址, 例如obj1 = obj2;

深复制,复制对象, 例如 obj2 = [obj1 ];

*** -[AddressBook copyWithZone:]: selector not recognized
*** Uncaught exception:
*** -[AddressBook copyWithZone:]: selector not recognized@interface Fraction: NSObject Fraction is a subclass of NSObject and conforms to the NSCopying protocol. In the implementation file Fraction.m, add the following definition for your new method:-(id) copyWithZone: (NSZone *) zone
{Fraction *newFract = [[Fraction allocWithZone: zone] init];[newFract setTo: numerator over: denominator];return newFract;
}

in and

-(void) setName: (NSString *) theName
{name = [theName copy];
}

19. with XML Lists

Mac OS X use XML () for such as your , , and , so it’s to know how to them and read them back in.

If your are of type , , , , , or , you can use :: in these to write your data to a file

#import int main (int argc, char * argv[])
{
@autoreleasepool {NSDictionary *glossary=[NSDictionarydictionaryWithObjectsAndKeys:@"A class defined so other classes can inheritfromit.",@"abstractclass",@"To implement all the methods defined inaprotocol",@"adopt",@"Storing an object for lateruse.",@"archiving",nil];if ([glossary writeToFile: @"glossary" atomically: YES] ==NO)NSLog (@"Save to filefailed!");
}
return 0;
}

with

#import 
int main (int argc, char * argv[])
{@autoreleasepool {NSDictionary *glossary =[NSDictionary dictionaryWithObjectsAndKeys:@"A class defined so other classes can inherit from it",@"abstract class",@"To implement all the methods defined in a protocol",@"adopt",@"Storing an object for later use",@"archiving",nil];[NSKeyedArchiver archiveRootObject: glossary toFile: @"glossary.archive"];}return 0;
}#import 
int main (int argc, char * argv[])
{@autoreleasepool {NSDictionary *glossary;glossary = [NSKeyedUnarchiver unarchiveObjectWithFile: @"glossary.archive"];for ( NSString *key in glossary )NSLog (@"%@: %@", key, [glossary objectForKey: key]);}       return 0;
}

and Using to

#import “AddressBook.h”
#import "Foo.h"
int main (int argc, char * argv[])
{@autoreleasepool {Foo *myFoo1 = [[Foo alloc] init];NSMutableData *dataArea;NSKeyedArchiver *archiver;AddressBook *myBook;// Insert code from Program 19.7 to create an Address Book// in myBook containing four address cards[myFoo1 setStrVal: @"This is the string"];[myFoo1 setIntVal: 12345];[myFoo1 setFloatVal: 98.6];// Set up a data area and connect it to an NSKeyedArchiver objectdataArea = [NSMutableData data];archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData: dataArea];// Now we can begin to archive objects[archiver encodeObject: myBook forKey: @"myaddrbook"];[archiver encodeObject: myFoo1 forKey: @"myfoo1"];[archiver finishEncoding];// Write the archived data area to a fileif ([dataArea writeToFile: @"myArchive" atomically: YES] == NO)NSLog (@"Archiving failed!");}return 0;}

Using the to Copy

You can use the ’s to a deep copy of an .

#import 
int main (int argc, char * argv[])
{@autoreleasepool {NSData *data;NSMutableArray *dataArray = [NSMutableArray arrayWithObjects:[NSMutableString stringWithString: @"one"],[NSMutableString stringWithString: @"two"],[NSMutableString stringWithString: @"three"],nil];NSMutableArray *dataArray2;NSMutableString *mStr;// Make a deep copy using the archiverdata = [NSKeyedArchiver archivedDataWithRootObject: dataArray];dataArray2 = [NSKeyedUnarchiver unarchiveObjectWithData: data];mStr = [dataArray2 objectAtIndex: 0];[mStr appendString: @"ONE"];NSLog (@"dataArray: ");for ( NSString *elem in dataArray )NSLog (@"%@", elem);NSLog (@"\ndataArray2: ");for ( NSString *elem in dataArray2 )NSLog (@"%@", elem);}return 0;
}

20 to CoCoa and Cocoa Touch

笔记阅读笔记__盗墓笔记阅读

21. iOS

关于我们

最火推荐

小编推荐

联系我们


版权声明:本站内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 88@qq.com 举报,一经查实,本站将立刻删除。备案号:桂ICP备2021009421号
Powered By Z-BlogPHP.
复制成功
微信号:
我知道了