Objective C UITableView模式背景

self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.png"]];

Objective C iPhone:隐藏状态栏(3.1,3.2和4.0的安全)

// setStatusBarHidden only on 3.2 and above.
		if([[UIApplication sharedApplication] respondsToSelector:@selector(setStatusBarHidden: withAnimation:)]) {
			[[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
		} else {
			[[UIApplication sharedApplication] setStatusBarHidden:NO animated:YES];
		}

Objective C VERBOSE_DEBUG_OUTPUT的宏

#ifdef VERBOSE_DEBUG_OUTPUT
	#warning Debugging output enabled
	#define NSDebug(x, ...) NSLog([ NSString stringWithFormat:@"%s: %@", __PRETTY_FUNCTION__, x], ## __VA_ARGS__ )
#else
	#define NSDebug(x, ...) /* x, ## __VA_ARGS__ */
#endif

Objective C 数组排序

// sorting the list by comparing the "date" property on the objects in the array
NSSortDescriptor *dateSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO selector:@selector(compare:)] autorelease];
[list sortUsingDescriptors:[NSArray arrayWithObjects:dateSortDescriptor, nil]];

Objective C 从iPhone获取设备GUID

UIDevice *device = [UIDevice currentDevice];
NSString *uniqueIdentifier = [device uniqueIdentifier];

Objective C 检查Internet连接

static BOOL checkNetwork = YES;
    if (checkNetwork) { // Since checking the reachability of a host can be expensive, cache the result and perform the reachability check once.
        checkNetwork = NO;
        
        Boolean success;    
        const char *host_name = "earthquake.usgs.gov";
		
        SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host_name);
        SCNetworkReachabilityFlags flags;
        success = SCNetworkReachabilityGetFlags(reachability, &flags);
        _isDataSourceAvailable = success && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired);
        CFRelease(reachability);
    }
    return _isDataSourceAvailable;

Objective C 使用NSNotificationCenter - 发布通知

NSNotificationCenter.

Mutliple observers can be notified of events.

notification sent by a specific object...
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFooHappened:) name:MyFooNotification object:foo];

set object to nil to receive notifications of that name sent by ANY object.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFooHappened:) name:MyFooNotification object:nil];

Format for myFooHappened is..
-(void) myFooHappened:(NSNotification*)note {
    // [note name] - name of notification [note object] - sender

    // [note userInfo] is an NSDictionary of key-value pairs filled by the sender. 
}

Note: notifications are posted on the SAME THREAD as they were posted.

MUST unregister from all notifications in your dealloc
-(void) dealloc
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

Posting a notification..
Define a constant for the name of the notification..
in .h
extern NSString* const MyFooNotification;

in .m
NSString* const MyFooNotification = @"MyFooNotification";

-(void) postFoo  {
[[NSNotificationCenter defaultCenter] postNotificationName:MyFooNotification object:self userInfo:[NSDictionary ...]];

Objective C 从URL加载图像

// NOTE: this uses place holders.
// PART 1 - update url of path to the image
// PART 2 - update the variable reference to the UIImageView object
// -----------------------------------------------

// ===== PART 1 =====
UIImage *imgURL = [[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: @"${part 1 image path:http://www.example.com/img.jpg}"]]] retain];

if (imgURL != nil) { // Image was loaded successfully.
	// ===== PART 2 =====
	[${part 2 UIImageView Ref:myMainImg} setImage:imgURL];
	// ===== PART 2 =====
	[${part 2 UIImageView Ref:myMainImg} setUserInteractionEnabled:NO];
	[imgURL release]; // Release the image now that we have a UIImageView that contains it.
}

Objective C 获取iPhone / iPad / iPod Touch硬件生成

#include <sys/sysctl.h>

+(NSString *)getPlatform {
  size_t size=0;
  char *machine=NULL;
  for(;;) {
    sysctlbyname("hw.machine",machine,&size,NULL,0);
    if(!size) break;
    if(machine) {
      NSString *platform=[NSString stringWithUTF8String:machine];
      free(machine);
      return platform;
    }
    machine=malloc(size);
    if(!machine) break;
  }
  return nil;
}

// optimistic version

+(NSString *)getPlatform {
  char machine[256];
  size_t size=sizeof(machine);
  sysctlbyname("hw.machine",machine,&size,NULL,0);
  return size>sizeof(machine) ? nil : [NSString stringWithUTF8String:machine];
}

Objective C 删除Documents文件夹中的文件

- (void)deleteFilesFromDocuments {
	NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
	NSFileManager* fm = [[[NSFileManager alloc] init] autorelease];
	NSDirectoryEnumerator* en = [fm enumeratorAtPath:path];    
	NSError* err = nil;
	BOOL res;
	NSString* file;
	while (file = [en nextObject]) {
		
		if ([file rangeOfString:@".sqlite"].location == NSNotFound) {
			res = [fm removeItemAtPath:[path stringByAppendingPathComponent:file] error:&err];
			if (!res && err) {
				NSLog(@"oops: %@", err);
			}
		}
	}
}