Search This Blog

Friday, February 26, 2010

C++ Vector

vector< int > ivec( 10, -1 );
定义了 ivec 它包含十个 int 型的元素 每个元素都被初始化为-1

// 把ia的6个元素拷贝到ivec中
vector< int > ivec( ia, ia+6 );
可以将 vector 初始化为一个已有数组的全部或一部分 只需指定希望被用来初始化 vector 的数组的开始地址以及数组最末元素的下一位置来实现

//拷贝3个元素 ia[2],ia[3],ia[4]
vector< int > ivec( &ia[ 2 ], &ia[ 5 ] );

与内置数组不同 vector 可以被另一个 vector 初始化 或被赋给另一个 vector
例如 vector< string > svec;

vector< string > svec;

void init_and_assign()
{
// 用另一个 vector 初始化一个
vector vector< string > user_names( svec );
// ...
// 把一个 vector 拷贝给另一个
vector svec = user_names;
}

Thursday, February 25, 2010

C++ 标准 STL(Standard Template Library)

在C++标准中,STL被组织为下面的13个头文件:

algorithm, deque, functional, iterator,
vector, list, map, memory, numeric,
queue, set, stack和utility

C++ 引用和指针的区别

指针和引用有两个主要区别 引用必须总是指向一个对象 如果用一个引用给另一个引 用赋值 那么改变的是被引用的对象而不是引用本身 让我们来看几个例子 当我们这样写
int *pi = 0;
用 0 初始化 pi——即 pi 当前不指向任何对象 但当我们写如下语句时 const int &ri = 0;
在内部 发生了以下转换
int temp = 0; const int &ri = temp;
引用之间的赋值是第二个不同 当给定了以下代码后
int ival = 1024, ival2 = 2048; int *pi = &ival, *pi2 = &ival2;
我们再写如下语句
pi = pi2;
pi 指向的对象 ival 并没有被改变 实际上 pi 被赋值为指向 pi2 所指的对象——在本例中 即 ival2 重要的是 现在 pi 和 pi2 都指向同一对象 这是一个重要的错误源 如果我们把 一个类对象拷贝给另一个类对象 而该类有一个或多个成员是指针 我们将在第 14 章详细讨 论这个问题
但是 假定有下列代码
int &ri = ival, &ri2 = ival2;
当我们写出这样的赋值语句时
ri = ri2;
改变的是 ival
而不是引用本身 赋值之后 两个引用仍然指向原来的对象 实际的 C++程序很少使用指向独立对象的引用类型 引用类型主要被用作函数的形式参数

Tuesday, February 23, 2010

Drawing with NSBezierPath



@interface StretchView : NSView {
NSBezierPath *path;
}
- (NSPoint)randomPoint;

@end

@implementation StretchView

- (id)initWithFrame:(NSRect)frame {
if (![super initWithFrame:frame])
return nil;

srandom(time(NULL));

path = [[NSBezierPath alloc] init];
[path setLineWidth:3.0];
NSPoint p = [self randomPoint];
[path moveToPoint:p];
int i;
for (i = 0; i < 15; i++) {
p = [self randomPoint];
[path lineToPoint:p];
}
[path closePath];
return self;
}

- (void)dealloc
{
[path release];
[super dealloc];
}

- (NSPoint)randomPoint
{
NSRect bounds = [self bounds];
NSPoint result;
result.x = bounds.origin.x + random() % (int)bounds.size.width;
result.y = bounds.origin.y + random() % (int)bounds.size.height;
return result;
}

- (void)drawRect:(NSRect)rect {
NSRect bounds = [self bounds];
[[NSColor greenColor] set];
[NSBezierPath fillRect:bounds];

[[NSColor whiteColor] set];
[path fill];

}

@end

Thursday, February 18, 2010

logging in iPhone Applications


NSData *dataToWrite = [[NSString stringWithString:@"String to write"] dataUsingEncoding:NSUTF8StringEncoding];

NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [docsDirectory stringByAppendingPathComponent:@"fileName.txt"];

// Write the file
[dataToWrite writeToFile:path atomically:YES];

// Read the file
NSString *stringFromFile = [[NSString alloc] initWithContentsOfFile:path];

// Check if file exists
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager fileExistsAtPath:path]; // Returns a BOOL

// Remove the file
[fileManager removeItemAtPath:path error:NULL];

// Cleanup
[stringFromFile release];
[fileManager release];


White log into the log-file

+ (void)logGenenalInfo:(NSString *)data {
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [docsDirectory stringByAppendingPathComponent:@"GeneralFile.txt"];

// Check if file exists
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:path]) {
// Read the file
NSString *stringFromFile = [[NSString alloc] initWithContentsOfFile:path];
data = [stringFromFile stringByAppendingFormat:@" %@",data];
}
NSData *dataToWrite = [data dataUsingEncoding:NSUTF8StringEncoding];
// Write the file
[dataToWrite writeToFile:path atomically:YES];
[fileManager release];
}


Clean the Log

+ (void)cleanAllLog {
NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *gePath = [docsDirectory stringByAppendingPathComponent:@"GeneralFile.txt"];


// Check if file exists then Remove the file
if ([fileManager fileExistsAtPath:gePath]) // Returns a BOOL
[fileManager removeItemAtPath:gePath error:NULL];

[fileManager release];
}


Get the program information

DateTime\tMessage\tData\tfileNameAndLineNumber

[LogFileHelper logGenenalInfo:
[NSString stringWithFormat:@"function %s, line %d \n"
,__FUNCTION__,__LINE__]];

Tuesday, February 16, 2010

iPhone-format


-(NSString*) formatCurrencyValue:(double)value
{
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setCurrencySymbol:@"$"];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber *c = [NSNumber numberWithFloat:value];
return [numberFormatter stringFromNumber:c];
}

-(NSString*) formatPercentValue:(double)value
{
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setPercentSymbol:@"%"];
[numberFormatter setNumberStyle: NSNumberFormatterPercentStyle];
[numberFormatter setDecimalSeparator:@"."];
[numberFormatter setGeneratesDecimalNumbers:TRUE];
[numberFormatter setMinimumFractionDigits:2];
[numberFormatter setRoundingMode: NSNumberFormatterRoundUp];
[numberFormatter setRoundingIncrement:[[NSNumber alloc]initWithDouble:0.05]];
NSNumber *c = [NSNumber numberWithFloat:value];
return [numberFormatter stringFromNumber:c];
}

-(double) formatDoubleFromCurrency:(NSString*)value
{
double ret ;
if(value)
{
ret = [value doubleValue];
if (ret == 0)
{
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setCurrencySymbol:@"$"];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber *c = [numberFormatter numberFromString:value];
ret = [c doubleValue];
}
return ret;
}
else
return 0.0;
}

Password Encryption


#import

@interface Encryption : NSObject {
}

+ (NSString *) md5: (NSString *) plainText;

@end



#import "Encryption.h"
#import

@implementation Encryption

+ (NSString *) md5: (NSString *) plainText {
const char *cStr = [plainText UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(cStr, strlen(cStr), result);

return [[NSString stringWithFormat: @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
] lowercaseString];
}

@end



+(NSString*)fileMD5:(NSString*)path
{
NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
if( handle== nil ) return @"ERROR GETTING FILE MD5"; // file didnt exist

CC_MD5_CTX md5;

CC_MD5_Init(&md5);

BOOL done = NO;
while(!done)
{
NSData* fileData = [handle readDataOfLength: CHUNK_SIZE ];
CC_MD5_Update(&md5, [fileData bytes], [fileData length]);
if( [fileData length] == 0 ) done = YES;
}
unsigned char digest[CC_MD5_DIGEST_LENGTH];
CC_MD5_Final(digest, &md5);
NSString* s = [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
digest[0], digest[1],
digest[2], digest[3],
digest[4], digest[5],
digest[6], digest[7],
digest[8], digest[9],
digest[10], digest[11],
digest[12], digest[13],
digest[14], digest[15]];
return s;
}

Monday, February 15, 2010

IPHONE APP 真正的全局变量

真正牛B 的全局变量是 定义在 main()里面的。。。。
可以直接用。。。。

Tuesday, February 9, 2010

iPhone-country code and iPhone locale settings

March 19, 2009 — praveenmatanam

NSLocale *locale = [NSLocale currentLocale];
NSString *countryCode = [locale objectForKey: NSLocaleCountryCode];

NSString *countryName = [locale displayNameForKey: NSLocaleCountryCode
value: countryCode]];

Sunday, February 7, 2010

Process status

ps -ax -o user,pid,vsz,rss,command


USER PID VSZ RSS COMMAND
root 1 2456680 1048 /sbin/launchd
root 10 2448264 2564 /usr/libexec/kextd
root 11 2444540 736 /usr/sbin/notifyd
root 12 2446808 1440 /usr/sbin/diskarbitrationd
root 13 2462636 3164 /usr/libexec/configd
root 14 2457096 852 /usr/sbin/syslogd
root 15 2452816 5012 /usr/sbin/DirectoryService
daemon 16 2446660 1596 /usr/sbin/distnoted
root 18 2459016 2452 /usr/sbin/cupsd -l
_usbmuxd 20 2460984 2024 /System/Library/PrivateFrameworks/MobileDevice.f
root 21 2446688 1008 /sbin/SystemStarter
root 24 2459344 3560 /usr/sbin/securityd -i
root 27 2809672 137060 /System/Library/Frameworks/CoreServices.framewor
_mdnsresponder 28 2459704 2376 /usr/sbin/mDNSResponder -launchd
ming 29 2777832 11236 /System/Library/CoreServices/loginwindow.app/Con
root 30 2445744 992 /usr/sbin/KernelEventAgent
root 32 2447564 2064 /usr/libexec/hidd
root 33 2464044 2560 /System/Library/Frameworks/CoreServices.framewor
root 35 2434784 788 /sbin/dynamic_pager -F /private/var/vm/swapfile
root 40 2461604 4260 /usr/sbin/blued
root 41 2445648 936 autofsd
root 45 105636 2792 /Library/Application Support/iStat Server/iStatS
root 49 2492500 27688 /System/Library/CoreServices/coreservicesd
_windowserver 60 2900984 110808 /System/Library/Frameworks/ApplicationServices.f
root 74 81940 444 /Library/Application Support/VMware Fusion/vmnet
root 80 81536 296 /Library/Application Support/VMware Fusion/vmnet
root 82 77668 176 /Library/Application Support/VMware Fusion/vmnet
root 85 77668 176 /Library/Application Support/VMware Fusion/vmnet
root 88 81536 288 /Library/Application Support/VMware Fusion/vmnet
root 90 88520 500 /Library/Application Support/VMware Fusion/vmnet
root 93 2438116 848 /System/Library/Frameworks/OpenGL.framework/Vers
_coreaudiod 104 2453356 6160 /usr/sbin/coreaudiod
ming 109 2456228 1100 /sbin/launchd
ming 113 2946424 22388 /System/Library/CoreServices/Dock.app/Contents/M
ming 114 2782252 20648 /System/Library/CoreServices/SystemUIServer.app/
ming 115 3109228 59456 /System/Library/CoreServices/Finder.app/Contents
ming 119 2435928 836 /usr/sbin/pboard
ming 122 2507916 5176 /System/Library/Frameworks/ApplicationServices.f
ming 127 2462084 1964 /System/Library/Frameworks/InputMethodKit.framew
ming 130 2725340 5648 /usr/libexec/UserEventAgent -l Aqua
ming 136 2447976 1644 /System/Library/CoreServices/AirPort Base Statio
ming 143 2727672 4876 /Applications/iTunes.app/Contents/Resources/iTun
ming 146 382580 2352 /Library/PreferencePanes/Microsoft Mouse.prefPan
ming 148 433900 7896 /Library/PreferencePanes/MaxMenus.prefPane/Conte
ming 149 387344 3768 /Users/ming/Library/Application Support/RealNetw
ming 150 502728 63288 /Applications/Dropbox.app/Contents/MacOS/Dropbox
root 153 98728 13328 /Users/ming/Library/Application Support/RealNetw
ming 157 2755412 7724 /System/Library/Image Capture/Support/Image Capt
ming 169 493260 15104 /Library/PreferencePanes/Growl.prefPane/Contents
root 186 602372 1432 /Applications/Dropbox.app/Contents/Resources/dbf
ming 191 2468332 9020 /System/Library/Services/AppleSpell.service/Cont
ming 208 2891412 299268 /System/Library/Frameworks/CoreServices.framewor
ming 319 2860440 38044 /System/Library/Input Methods/SCIM.app/Contents/
ming 367 2181412 341968 /Applications/Firefox.app/Contents/MacOS/firefox
ming 395 602576 94244 /Applications/Microsoft Office 2008/Microsoft Po
ming 398 424872 7724 /Applications/Microsoft Office 2008/Office/Micro
ming 400 368980 2116 /Library/Application Support/Microsoft/MAU2.0/Mi
ming 523 634040 47896 /Applications/iTunes.app/Contents/MacOS/iTunes -
ming 524 110844 9796 /System/Library/PrivateFrameworks/MobileDevice.f
ming 725 11324624 83240 /Developer/Applications/Xcode.app/Contents/MacOS
ming 954 2864280 15080 /Applications/Utilities/Terminal.app/Contents/Ma
ming 1360 2855608 49036 /Applications/Mail.app/Contents/MacOS/Mail -psn_
ming 1458 2458404 1412 /usr/bin/ssh-agent -l
ming 1692 501360 14980 /Applications/TextWrangler.app/Contents/MacOS/Te
ming 1695 101004 956 /Applications/TextWrangler.app/Contents/Helpers/
ming 2381 2775268 24184 /Applications/iCal.app/Contents/MacOS/iCal -psn_
ming 2403 3033012 94076 /Applications/Preview.app/Contents/MacOS/Preview
_lp 4284 2467040 32676 Brother_HL_2170W_series 7 ming 1-02 Session 101
root 4285 2435912 840 mdns://Brother%20HL-2170W%20series._pdl-datastre
ming 4294 691276 73032 /Applications/QQ.app/Contents/MacOS/QQ -psn_0_99
root 4538 2436056 1588 login -pf ming
ming 4539 2435468 1092 -bash
root 5099 2434788 516 ps -ax -o user,pid,vsz,rss,command

Tuesday, February 2, 2010

Play sound


#import


@interface CSSound : NSObject {

}
+(void)playSound:(NSString *)soundName;
@end


#import "CSSound.h"
#import

@implementation CSSound
+(void)playSound:(NSString *)soundName{
SystemSoundID mySSID;
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingString:soundName];

OSStatus error = AudioServicesCreateSystemSoundID( (CFURLRef)[NSURL fileURLWithPath:path], &mySSID);

if(error == kAudioServicesNoError){
//DLog(@"successfully contructed sound %@", soundName);
AudioServicesPlaySystemSound(mySSID);
}else{
DLog(@"error playing sound %@", soundName);
}
}

Monday, February 1, 2010

gcc Unix&Mac OS program (3. Predefined macros)

__APPLE__ : Defined for an Apple Platform, such as OS X.
__APPLE_CC__ : This is an integer value representing the version of the compiler.
__OBJC__ : Defined if the compiler is compiling in Objective-C mode
__cplusplus : Defined if the compiler is compiling in C++ mode.
__MACH__ : Defined if the Mach system calls are available
__DATE__ : The current date
__TIME__ : The current time
__FILE__ : The name of file
__LINE__ : The line number of the file
__FUNCTION__ : The name of the function r Objective-C method being compiled


// predef.m -- play with predefined macros

/* compile with
cc -g -Wall -o predef -framework Foundation predef.m
*/


#import
#import

void someFunc (void)
{
printf ("file %s, line %d, function %s\n", __FILE__, __LINE__, __FUNCTION__);
} // someFunc

@interface SomeClass : NSObject { }
+ (void) someMethod;
@end

@implementation SomeClass
+ (void) someMethod
{
printf ("file %s, line %d, function %s\n", __FILE__, __LINE__, __FUNCTION__);
} // someMethod
@end

int main (int argc, char *argv[])
{
printf ("__APPLE__: %d, __APPLE_CC__: %d\n",
__APPLE__, __APPLE_CC__);
printf ("today is %s, the time is %s\n", __DATE__, __TIME__);
printf ("file %s, line %d, function %s\n", __FILE__, __LINE__, __FUNCTION__);
someFunc ();
[SomeClass someMethod];
return (0);
} // main


cc -g -Wall -o predef -framework Foundation predef.m

./predef

__APPLE__: 1, __APPLE_CC__: 5657
today is Feb 1 2010, the time is 12:32:23
file predef.m, line 32, function main
file predef.m, line 13, function someFunc
file predef.m, line 23, function +[SomeClass someMethod]

gcc Unix&Mac OS program (2. assemble resulting file)

cc -g -Wall -S XXXX.m

cc -o xxxx xxxx.s

gcc Unix&Mac OS program (1. Warning)


int main (int arg, char *argv)
{
int i;
}


terminal command: cc -Wall -o warning warning.m

warning.m:2: warning: second argument of ‘main’ should be ‘char **’
warning.m: In function ‘main’:
warning.m:3: warning: unused variable ‘i’
warning.m:4: warning: control reaches end of non-void function

/*
* cc - Wall -Wno-unused warning.m (turn that unused warning off)
*/

/*
* cc -Wunused warning.m (only see unused warning mistakes)
*/