1.#import 保证头文件只被包含一次,无论该命令出现多少次。
2.cocoa组成部分—Foundation
—Application Kit(包含许多cocoa高级特性:用户界面元素,打印,颜色,声音,AppleScript)
—支持框架—Core Animation
—Core Image
3.NSLog()和@”字符串”
cocoa的所有函数,变量,类型都是NS前缀。自定义不用使用前缀NS。
@符号意味着引号内的字符串作为cocoa的NSString元素来处理。
4.BOOL
是一种对带符号的字符类型(signed char)的类型定义typedef,使用8位存储空间。
#import <Foundation/Foundation.h>
//return NO if the two integers have the same
//value, YES otherwise
BOOL areIntsDifferent (int thing1, int thing2)
{
if (thing1 == thing2) {
return (NO);
} else {
return (YES);
}
}//areIntsDifferent
//given a NO value, return the human-readable
//string “NO”. Otherwise return “YES”
NSString *boolString (BOOL yesNo)
{
if (yesNo ==NO) {
return (@”NO”);
} else {
return (@”YES”);
}
}//boolString
int main (int argc, const char *argv[])
{
BOOL areTheyDifferent;
areTheyDifferent = areIntsDifferent(5, 5);
NSLog(@”are %d and %d different? %@”, 5, 5, boolString(areTheyDifferent));
return (0);
}//main
注意:使用NSLog()输出任意对象的值时,都会使用%@格式来表示。在使用这个说明符时,对象会通过一个名字为description的方法提供自己的NSLog()格式。NSString的description方法可简单输出字符串中的字符。
#import <Foundation/Foundation.h>
int main (int argc, const char *argv[])
{
int count = 5;
NSLog(@”The numbers from 1 to %d:”, count);
for (int i=1; i<=count; i++) {
NSLog(@”%d\n”, i);
}
return (0);
}
#import <Foundation/Foundation.h>
int main (int argc, const char *argv[])
{
FILE *wordFile = fopen(“/tmp/words.txt”, “r”);
char word[100];
while (fgets(word, 100, wordFile))
{
//strip off the trailing \n
word[strlen(word) – 1] = ‘\0’;
NSLog(@”%s is %lu characters long”, word, strlen(word));
}
fclose(wordFile);
return (0);
}//main
Joe-Bob “handyman” Brown
Jacksonville “Sly” Murphy
George “Guitar” Books