(轉載)ios開發知識總結 — 下

酷行僧發表於2014-08-21
三:使用NSXMLParser解析xml檔案



    1. 設定委託物件,開始解析

    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];   //或者也可以使用initWithContentsOfURL直接下載檔案,但是有一個原因不這麼做:

    // It`s also possible to have NSXMLParser download the data, by passing it a URL, but this is not desirable

    // because it gives less control over the network, particularly in responding to connection errors.

    [parser setDelegate:self];

    [parser parse];



    2. 常用的委託方法

    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName

                                namespaceURI:(NSString *)namespaceURI

                                qualifiedName:(NSString *)qName

                                attributes:(NSDictionary *)attributeDict;

    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName

                                namespaceURI:(NSString *)namespaceURI

                                qualifiedName:(NSString *)qName;

    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string;

    - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError;



    static NSString *feedURLString = @"http://www.yifeiyang.net/test/test.xml";



    3.  應用舉例

    - (void)parseXMLFileAtURL:(NSURL *)URL parseError:(NSError **)error

    {

        NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:URL];

        [parser setDelegate:self];

        [parser setShouldProcessNamespaces:NO];

        [parser setShouldReportNamespacePrefixes:NO];

        [parser setShouldResolveExternalEntities:NO];

        [parser parse];

        NSError *parseError = [parser parserError];

        if (parseError && error) {

            *error = parseError;

        }

        [parser release];

    }



    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI

                                        qualifiedName:(NSString*)qName attributes:(NSDictionary *)attributeDict{

        // 元素開始控制程式碼

        if (qName) {

            elementName = qName;

        }

        if ([elementName isEqualToString:@"user"]) {

            // 輸出屬性值

            NSLog(@"Name is %@ , Age is %@", [attributeDict objectForKey:@"name"], [attributeDict objectForKey:@"age"]);

        }

    }



    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI

                                        qualifiedName:(NSString *)qName

    {

        // 元素終了控制程式碼

        if (qName) {

               elementName = qName;

        }

    }



    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string

    {

        // 取得元素的text

    }



    NSError *parseError = nil;

    [self parseXMLFileAtURL:[NSURL URLWithString:feedURLString] parseError:&parseError];



Iphone 實現畫折線圖



iphone裡面要畫圖一般都是通過CoreGraphics.framwork和QuartzCore.framwork實現,apple的官方sdk demon中包含了QuartzCore的基本用法,




具體demo請參考http://developer.apple.com/library/ios/#samplecode/QuartzDemo/

折線圖





要實現折線圖也就把全部的點連起來,movePointLineto,具體的呼叫裡面的api就可以實現了,但是畫座標就比較麻煩了,裡面需要去轉很多,好在國外有人開源了一個畫折線圖的開發包,首先看看效果吧,具體怎麼用可以參考作者git版本庫中的wiki。

http://github.com/devinross/tapkulibrary/wiki/How-To-Use-This-Library


這個包還提供了其他的很好看的UI,都可以調來用,但是我們只需要一個畫圖要把整個包都導進去,工程太大了,既然是開源的那就想辦法提取出來吧,原先之前也有人幹過這樣的事。http://duivesteyn.net/2010/03/07/iphone-sdk-implementing-the-tapku-graph-in-your-application/

我對原始碼進行簡單的修改,使其顯示座標之類的,更加符合工程的需要,但是還沒有實現畫多組資料,只能畫一組資料,不用viewContol,而使用addsubview,直接新增到當前的視窗,最終效果如下。

使用方法:


1.工程新增tk庫裡面的如下檔案


2. 新增QuartzCore  framework

#import <QuartzCore/QuartzCore.h>

新增TapkuLibrary.bundle資原始檔

3.程式碼中完成例項,資料初始化就可以用了


下載修改後的版本。下次有時間在整理一個工程版本出來。



讓iPhone螢幕常亮不變暗的方法



如果您希望執行自己開發的App時,iPhone的螢幕不再自動變暗,可以使用以下方法讓螢幕常亮: iPhone OS用一個布林值用來控制是否取消應用程式空閒時間:@property(nonatomic, getter=isIdleTime



如果您希望執行自己開發的App時,iPhone的螢幕不再自動變暗,可以使用以下方法讓螢幕常亮:



  iPhone OS用一個布林值用來控制是否取消應用程式空閒時間:@property(nonatomic, getter=isIdleTimerDisabled) BOOL idleTimerDisabled。這個值的預設屬性是"NO"。當大多數應用程式沒有接收到使用者輸入資訊的時候,系統會把裝置設定成“休眠”狀態,iPhone螢幕也會變暗。這樣做是為了儲存更多電量。事實上,應用程式在執行加速度遊戲的時候是不需要使用者輸入的,當然這裡只是一個假設,把這個變數設定為"YES",來取消系統休眠的“空閒時間”。



重點是:你必須當真正需要的時候才開啟這個屬性當你不用的時候馬上還願成"NO"。大多數應用程式在休眠時間到的時候讓系統關閉螢幕。這個包括了有音訊的應用程 序。在Audio Session Services中使用適當的回放和記錄功能不會被間斷當螢幕關閉時。只有地圖應用程式,遊戲或者一些不間斷的使用者互動程式可以取消這個屬性。



蘋果開發網路程式設計知識總結



以下蘋果開發網路程式設計知識由 CocoaChina 會員 cocoa_yang 總結,希望能為蘋果開發新手梳理知識脈絡,節省入門時間。一:確認網路環境3G/WIFI 1. 新增原始檔和framework 開發Web等網路應用程式



  以下蘋果開發網路程式設計知識由 CocoaChina 會員 “cocoa_yang” 總結,希望能為蘋果開發新手梳理知識脈絡,節省入門時間。



一:確認網路環境3G/WIFI



    1. 新增原始檔和framework



    開發Web等網路應用程式的時候,需要確認網路環境,連線情況等資訊。如果沒有處理它們,是不會通過Apple的審查的。

    Apple 的 例程 Reachability 中介紹了取得/檢測網路狀態的方法。要在應用程式程式中使用Reachability,首先要完成如下兩部:



    1.1. 新增原始檔:

    在你的程式中使用 Reachability 只須將該例程中的 Reachability.h 和 Reachability.m 拷貝到你的工程中。如下圖:



    1.2.新增framework:

    將SystemConfiguration.framework 新增進工程。如下圖:





    2. 網路狀態



    Reachability.h中定義了三種網路狀態:

    typedef enum {

        NotReachable = 0,            //無連線

        ReachableViaWiFi,            //使用3G/GPRS網路

        ReachableViaWWAN            //使用WiFi網路

    } NetworkStatus;



    因此可以這樣檢查網路狀態:



    Reachability *r = [Reachability reachabilityWithHostName:@“www.apple.com”];

    switch ([r currentReachabilityStatus]) {

            case NotReachable:

                    // 沒有網路連線

                    break;

            case ReachableViaWWAN:

                    // 使用3G網路

                    break;

            case ReachableViaWiFi:

                    // 使用WiFi網路

                    break;

    }



    3.檢查當前網路環境



    程式啟動時,如果想檢測可用的網路環境,可以像這樣

    // 是否wifi

    + (BOOL) IsEnableWIFI {

        return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);

    }



    // 是否3G

    + (BOOL) IsEnable3G {

        return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);

    }

    例子:

    - (void)viewWillAppear:(BOOL)animated {   

    if (([Reachability reachabilityForInternetConnection].currentReachabilityStatus == NotReachable) &&

            ([Reachability reachabilityForLocalWiFi].currentReachabilityStatus == NotReachable)) {

            self.navigationItem.hidesBackButton = YES;

            [self.navigationItem setLeftBarButtonItem:nil animated:NO];

        }

    }



    4. 連結狀態的實時通知



    網路連線狀態的實時檢查,通知在網路應用中也是十分必要的。接續狀態發生變化時,需要及時地通知使用者:



    Reachability 1.5版本

    // My.AppDelegate.h

    #import "Reachability.h"



    @interface MyAppDelegate : NSObject <UIApplicationDelegate> {

        NetworkStatus remoteHostStatus;

    }



    @property NetworkStatus remoteHostStatus;



    @end



    // My.AppDelegate.m

    #import "MyAppDelegate.h"



    @implementation MyAppDelegate

    @synthesize remoteHostStatus;



    // 更新網路狀態

    - (void)updateStatus {

        self.remoteHostStatus = [[Reachability sharedReachability] remoteHostStatus];

    }



    // 通知網路狀態

    - (void)reachabilityChanged:(NSNotification *)note {

        [self updateStatus];

        if (self.remoteHostStatus == NotReachable) {

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"AppName", nil)

                         message:NSLocalizedString (@"NotReachable", nil)

                        delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];

            [alert show];

            [alert release];

        }

    }



    // 程式啟動器,啟動網路監視

    - (void)applicationDidFinishLaunching:(UIApplication *)application {



        // 設定網路檢測的站點

        [[Reachability sharedReachability] setHostName:@"www.apple.com"];

        [[Reachability sharedReachability] setNetworkStatusNotificationsEnabled:YES];

        // 設定網路狀態變化時的通知函式

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:)

                                                 name:@"kNetworkReachabilityChangedNotification" object:nil];

        [self updateStatus];

    }



    - (void)dealloc {

        // 刪除通知物件

        [[NSNotificationCenter defaultCenter] removeObserver:self];

        [window release];

        [super dealloc];

    }



    Reachability 2.0版本





    // MyAppDelegate.h

    @class Reachability;



        @interface MyAppDelegate : NSObject <UIApplicationDelegate> {

            Reachability  *hostReach;

        }



    @end



    // MyAppDelegate.m

    - (void)reachabilityChanged:(NSNotification *)note {

        Reachability* curReach = [note object];

        NSParameterAssert([curReach isKindOfClass: [Reachability class]]);

        NetworkStatus status = [curReach currentReachabilityStatus];



        if (status == NotReachable) {

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"AppName""

                              message:@"NotReachable"

                              delegate:nil

                              cancelButtonTitle:@"YES" otherButtonTitles:nil];

                              [alert show];

                              [alert release];

        }

    }



    - (void)applicationDidFinishLaunching:(UIApplication *)application {

        // ...



        // 監測網路情況

        [[NSNotificationCenter defaultCenter] addObserver:self

                              selector:@selector(reachabilityChanged:)

                              name: kReachabilityChangedNotification

                              object: nil];

        hostReach = [[Reachability reachabilityWithHostName:@"www.google.com"] retain];

        hostReach startNotifer];

        // ...

    }





二:使用NSConnection下載資料



    1.建立NSConnection物件,設定委託物件



    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self urlString]]];

    [NSURLConnection connectionWithRequest:request delegate:self];



    2. NSURLConnection delegate委託方法

        - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response; 

        - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error; 

        - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; 

        - (void)connectionDidFinishLoading:(NSURLConnection *)connection; 



    3. 實現委託方法

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

        // store data

        [self.receivedData setLength:0];            //通常在這裡先清空接受資料的快取

    }



    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

           /* appends the new data to the received data */

        [self.receivedData appendData:data];        //可能多次收到資料,把新的資料新增在現有資料最後

    }



    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

        // 錯誤處理

    }



    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {

        // disconnect

        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 

        NSString *returnString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];

        NSLog(returnString);

        [self urlLoaded:[self urlString] data:self.receivedData];

        firstTimeDownloaded = YES;

    }



三:使用NSXMLParser解析xml檔案



    1. 設定委託物件,開始解析

    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];   //或者也可以使用initWithContentsOfURL直接下載檔案,但是有一個原因不這麼做:

    // It`s also possible to have NSXMLParser download the data, by passing it a URL, but this is not desirable

    // because it gives less control over the network, particularly in responding to connection errors.

    [parser setDelegate:self];

    [parser parse];



    2. 常用的委託方法

    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName

                                namespaceURI:(NSString *)namespaceURI

                                qualifiedName:(NSString *)qName

                                attributes:(NSDictionary *)attributeDict;

    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName

                                namespaceURI:(NSString *)namespaceURI

                                qualifiedName:(NSString *)qName;

    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string;

    - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError;



    static NSString *feedURLString = @"http://www.yifeiyang.net/test/test.xml";



    3.  應用舉例

    - (void)parseXMLFileAtURL:(NSURL *)URL parseError:(NSError **)error

    {

        NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:URL];

        [parser setDelegate:self];

        [parser setShouldProcessNamespaces:NO];

        [parser setShouldReportNamespacePrefixes:NO];

        [parser setShouldResolveExternalEntities:NO];

        [parser parse];

        NSError *parseError = [parser parserError];

        if (parseError && error) {

            *error = parseError;

        }

        [parser release];

    }



    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI

                                        qualifiedName:(NSString*)qName attributes:(NSDictionary *)attributeDict{

        // 元素開始控制程式碼

        if (qName) {

            elementName = qName;

        }

        if ([elementName isEqualToString:@"user"]) {

            // 輸出屬性值

            NSLog(@"Name is %@ , Age is %@", [attributeDict objectForKey:@"name"], [attributeDict objectForKey:@"age"]);

        }

    }



    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI

                                        qualifiedName:(NSString *)qName

    {

        // 元素終了控制程式碼

        if (qName) {

               elementName = qName;

        }

    }



    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string

    {

        // 取得元素的text

    }



    NSError *parseError = nil;

    [self parseXMLFileAtURL:[NSURL URLWithString:feedURLString] parseError:&parseError];



如何隱藏狀態列

[ UIApplication sharedApplication ].statusBarHidden = YES;



.m 檔案與.mm檔案的區別

.m檔案是object-c檔案

.mm檔案相當於c++或者c檔案



NSLog(@"afd")與 NSLog("afd")



細微差別會導致程式崩潰。



但是我不太明白為何蘋果要把編譯器做的對這兩種常量有區別。



不過值得一提的是可能為了方便蘋果自身的NSObject物件的格式化輸出。



safari其實沒有把記憶體的快取寫到儲存卡上



NSURLCache doesn`t seem to support writing to disk on iPhone. The documentation for NSCachedURLResponse says that the NSURLCacheStoragePolicy "NSURLCacheStorageAllowed" is treated as "NSURLCacheStorageAllowedInMemoryOnly" by iPhone OS.



官方文件是這麼說的。



為了證明這個,我找到了一個目錄。



/private/var/mobile/Library/Caches/Safari/Thumbnails



隨機數的使用



        標頭檔案的引用

        #import <time.h>

        #import <mach/mach_time.h>



        srandom()的使用

        srandom((unsigned)(mach_absolute_time() & 0xFFFFFFFF));



        直接使用 random() 來呼叫隨機數



在UIImageView 中旋轉影像



        float rotateAngle = M_PI;

        CGAffineTransform transform =CGAffineTransformMakeRotation(rotateAngle);

        imageView.transform = transform;



        以上程式碼旋轉imageView, 角度為rotateAngle, 方向可以自己測試哦!





在Quartz中如何設定旋轉點



        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg.png"]];

        imageView.layer.anchorPoint = CGPointMake(0.5, 1.0);



        這個是把旋轉點設定為底部中間。記住是在QuartzCore.framework中才得到支援。



建立.plist檔案並儲存



        NSString *errorDesc;  //用來存放錯誤資訊

        NSMutableDictionary *rootObj = [NSMutableDictionary dictionaryWithCapacity:4]; //NSDictionary, NSData等檔案可以直接轉化為plist檔案

        NSDictionary *innerDict;

        NSString *name;

        Player *player;

        NSInteger saveIndex;



        for(int i = 0; i < [playerArray count]; i++) {

              player = nil;

              player = [playerArray objectAtIndex:i];

              if(player == nil)

                     break;

              name = player.playerName;// This "Player1" denotes the player name could also be the computer name

              innerDict = [self getAllNodeInfoToDictionary:player];

              [rootObj setObject:innerDict forKey:name]; // This "Player1" denotes the person who start this game

        }

        player = nil;

        NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:(id)rootObj format:NSPropertyListXMLFormat_v1_0 errorDescription:&errorDesc];



        紅色部分可以忽略,只是給rootObj新增一點內容。這個plistData為建立好的plist檔案,用其writeToFile方法就可以寫成檔案。下面是程式碼:



        /*得到移動裝置上的檔案存放位置*/

        NSString *documentsPath = [self getDocumentsDirectory];

        NSString *savePath = [documentsPath stringByAppendingPathComponent:@"save.plist"];



        /*存檔案*/

        if (plistData) {

                [plistData writeToFile:savePath atomically:YES];

         }

         else {

                NSLog(errorDesc);

                [errorDesc release];

        }



        - (NSString *)getDocumentsDirectory { 

                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

                return [paths objectAtIndex:0]; 

        }



讀取plist檔案並轉化為NSDictionary



        NSString *documentsPath = [self getDocumentsDirectory];

        NSString *fullPath = [documentsPath stringByAppendingPathComponent:@"save.plist"];

        NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:fullPath];



讀取一般性文件檔案



        NSString *tmp;

        NSArray *lines; /*將檔案轉化為一行一行的*/

        lines = [[NSString    stringWithContentsOfFile:@"testFileReadLines.txt"]

                       componentsSeparatedByString:@"
"];



         NSEnumerator *nse = [lines objectEnumerator];



         // 讀取<>裡的內容

         while(tmp = [nse nextObject]) {

                  NSString *stringBetweenBrackets = nil;

                  NSScanner *scanner = [NSScanner scannerWithString:tmp];

                  [scanner scanUpToString:@"<" intoString:nil];

                  [scanner scanString:@"<" intoString:nil];

                  [scanner scanUpToString:@">" intoString:&stringBetweenBrackets];



                  NSLog([stringBetweenBrackets description]);

          }



對於讀寫檔案,還有補充,暫時到此。隨機數和檔案讀寫在遊戲開發中經常用到。所以把部分內容放在這,以便和大家分享,也當記錄,便於查詢。



隱藏NavigationBar

[self.navigationController setNavigationBarHidden:YES animated:YES];



在想隱藏的ViewController中使用就可以了。



如何在iPhone程式中呼叫外部命令



下面是如何在iPhone非官方SDK程式中呼叫外部命令的方法。



- ( NSString * ) executeCommand : ( NSString * ) cmd { NSString * output = [ NSString string ] ; FILE * pipe = popen ( [ cmd cStringUsingEncoding : NSASCIIStringEnc

  

下面是如何在iPhone非官方SDK程式中呼叫外部命令的方法。



- (NSString *)executeCommand: (NSString *)cmd

{

    NSString *output = [NSString string];

    FILE *pipe = popen([cmd cStringUsingEncoding: NSASCIIStringEncoding], "r");

    if (!pipe) return;



    char buf[1024];

    while(fgets(buf, 1024, pipe)) {

    output = [output stringByAppendingFormat: @"%s", buf];

}



pclose(pipe);

return output;

}



NSString *yourcmd = [NSString stringWithFormat: @"your command"];

[self executeCommand: yourcmd];



如何在iPhone程式讀取資料時顯示進度窗



下面程式碼說明如何使用iPhone 非官方SDK在讀取資料時顯示進度條。



以下程式碼參考了MobileRss。



定義標頭檔案:



#import "uikit/UIProgressHUD.h"



@interface EyeCandy : UIApplication {

 UIProgressHUD *progress;

}



- (void) showProgressHUD:(NSString *)label withWindow:(UIWindow *)w withView:(UIView *)v withRect:(struct CGRect)rect;

- (void) hideProgressHUD;



.@end



上面的引號要改成<>。



import "EyeCandy.h"



@implementation EyeCandy

- (void)showProgressHUD:(NSString *)label withWindow:(UIWindow *)w withView:(UIView *)v withRect:(struct CGRect)rect

{

 progress = [[UIProgressHUD alloc] initWithWindow: w];

 [progress setText: label];

 [progress drawRect: rect];

 [progress show: YES];



 [v addSubview:progress];

}



- (void)hideProgressHUD

{

 [progress show: NO];

 [progress removeFromSuperview];

}



@end



使用下面程式碼呼叫:



// Setup Eye Candy View

_eyeCandy = [[[EyeCandy alloc] init] retain];



// Call loading display

[_eyeCandy showProgressHUD:@"Loading …" withWindow:window withView:mainView withRect:CGRectMake(0.0f, 100.0f, 320.0f, 50.0f)];



// When finished for hiding the &quot;loading text&quot;

[_eyeCandy hideProgressHUD];



WebKit的基本用法



WebKit是蘋果開發中比較常用的瀏覽器引擎,Safari使用的正是WebKit引擎。WebKit基於KDE的KHTML加以再開發,解析速度超過了以往所有的瀏覽器。這裡簡單記錄一下WebKit的基本用法。



WebKit由下面的結構組成:



•DomCore

•JavaScriptCore

•WebCore

一般瀏覽



要開啟網頁,可以這樣做:



1.[[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlText]]];

DomCore



DomCore用於處理DOM文件,包括:



•DOMDocument

•DOMNamedNodeMap

•DOMNode

•DOMNodeList

要獲取一個DOMDocument,可以這樣做:



1.DOMDocument *myDOMDocument = [[webView mainFrame] DOMDocument];

要用於HTML處理,可以使用DOMHTMLDocument(Mac OS X 10.4之後),獲取方式相同:



1.DOMHTMLDocument *myDOMDocument = (DOMHTMLDocument*)[[webView mainFrame] DOMDocument];

方法定義:



蘋果的WebKit更新說明



JavaScriptCore



在WebKit中執行指令碼的方法:



1.WebScriptObject *myscript = [webView windowScriptObject];

2.NSString *script = @"alert(`hello`);";

3.[myscript evaluateWebScript script];

參考:



http://www.macgood.com/thread-24636-1-1.html



http://www.cocoadev.com/index.pl?WebKit



為什麼不要做iPhone上面的應用



簡單來說就是因為兩國的文化不同,或者說生活方式的不同。美國不管多窮的人都有車,他們平時的生活方式和國內絕對是完全不同的。做應用和做遊戲不一樣,應用需要滿足人們某一

  簡單來說就是因為兩國的文化不同,或者說生活方式的不同。美國不管多窮的人都有車,他們平時的生活方式和國內絕對是完全不同的。做應用和做遊戲不一樣,應用需要滿足人們某一部分的需求,比如,一個計算小費的軟體,在國內不會有市場,可是美國人都有一個。

大家可以設身處地的想一下,誰會需要你做的軟體,這樣的人有多少,這樣的人又有iPhone的又有多少。



對於應用來說,針對商務人士的又比針對普通人的好,基本上商務人士不太在乎幾塊錢一個軟體,這也是backup assistant賣得最好的一個原因。這個軟體一年的年費24美元,大約有數千萬美元一年的收入。什麼樣的應用軟體是這些人需要的?連筆者自己也不太清楚,筆者雖然已經在美國工作了多年,但是對於美國文化的瞭解還處於一知半解狀態,更不用說正在留學的學生了。



還有一個能成功的應用軟體是你已經有非常多的資料,比如你有當地的所有加油站的資訊,做一個油價的地圖軟體,顯然市場會不錯。不過資料要是美國的資料,國內的沒有太大的幫助。



綜上所述,遊戲比應用好做很多,如果要作應用的話,可以從單機的小應用開始。要在美國運營一個支援10萬人的網路應用,沒有30萬美元絕對沒戲。如果非要上,只能早死早超生了。



獲取iPhone使用者手機號



使用下面的函式可以返回使用者的手機號:



extern NSString *CTSettingCopyMyPhoneNumber();



然後呼叫即可。



由於這個函式是包含在CoreTelephony中,所以只能用於非官方iPhone SDK。



在程式中關閉iPhone

首先在程式中引用 #include sys/reboot.h 然後使用 reboot(RB_HALT); 就可以直接將iPhone關機。

  

首先在程式中引用



#include <sys/reboot.h>



然後使用



reboot(RB_HALT);



就可以直接將iPhone關機。



convert the contents of an NSData object to an NSString



1. NSString *stringFromASC = [NSString stringWithCString:[ascData bytes] length:[ascData length]];



If the NSData object contains unichar characters then do this:



NSString *stringFromUnichar = [NSString stringWithCharacters:[unicharData bytes] length:[unicharData length] / sizeof(unichar)];



2. - (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding



iPhone的特殊URL

在iPhone中,可以直接用UIApp開啟URL地址。如下所示:



1.[ UIApp openURL: [ NSURL URLWithString:@"http://www.apple.com" ] ];

或者:



1.[ UIApp openURL: [ NSURL URLWithString:@"mailto:apple@mac.com?Subject=hello" ] ];

與此同時,iPhone還包含一些其他除了http://或者mailto:之外的URL:



sms:// 可以呼叫簡訊程式



tel:// 可以撥打電話



itms:// 可以開啟MobileStore.app



audio-player-event:// 可以開啟iPod



audio-player-event://?uicmd=show-purchased-playlist 可以開啟iPod播放列表



video-player-event:// 可以開啟iPod中的視訊





get iphone uniqueIdentifier



I also find that I can get uniqueIdentifier using:



UIDevice *myDevice = [UIDevice currentDevice];NSString *identifier = myDevice.uniqueIdentifier;





開啟本地網頁,與遠端網頁



fileURLWithPath:Initializes and returns a newly created NSURL object as a file URL with a specified path.



+ (id)fileURLWithPath:(NSString *)path



URLWithString:

Creates and returns an NSURL object initialized with a provided string.



+ (id)URLWithString:(NSString *)URLString



教你如何使用UIWebView



Start by opening up the WebBrowserTutorialAppDelegate.h file and editing the @interface line to read:



@interface WebBrowserTutorialAppDelegate : NSObject <UIWebViewDelegate> {

What we have done is to make the main AppDelegate a delegate for the UIWebView as well.



Now we need to set our webView to have the main AppDelegate as its delegate, you can do this by opening up WebBrowserTutorialAppDelegate.m and putting the following line just inside theapplicationDidFinishLaunching function:



webView.delegate = self;

That is all pretty self explanatory, it just sets the delegate of our webView to self, which in this case is our main application delegate.



Now we are pretty much done, we just need to add the function to catch the link clicks. To do this we need to add a new function, copy the content below to the WebBrowserTutorialAppDelegate.m file:



- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {

       NSURL *url = request.URL;

       NSString *urlString = url.absoluteString;

       NSLog(urlString);

       return YES;

}

This function will catch all requests and allow you to either manipulate them and pass them on or to perform your own custom action and stop the event from bubbling.



The first line gets the URL of the request, this is the contents inside the href attribute in the anchor tag.

The next line converts the URL to a string so we can log it out. You can access many parts of the NSURL, here are some of them and brief description of what they do.



* absoluteString - An absolute string for the URL. Creating by resolving the receiver’s string against its base.

* absoluteURL - An absolute URL that refers to the same resource as the receiver. If the receiver is already absolute, returns self.

* baseURL - The base URL of the receiver. If the receiver is an absolute URL, returns nil.

* host - The host of the URL.

* parameterString - The parameter string of the URL.

* password - The password of the URL (i.e. http://user:pass@www.test.com would return pass)

* path - Returns the path of a URL.

* port - The port number of the URL.

* query - The query string of the URL.

* relativePath - The relative path of the URL without resolving against the base URL. If the receiver is an absolute URL, this method returns the same value as path.

* relativeString - string representation of the relative portion of the URL. If the receiver is an absolute URL this method returns the same value as absoluteString.

* scheme - The resource specifier of the URL (i.e. http, https, file, ftp, etc).

* user - The user portion of the URL.



Then the third line simply logs the URL to the console, so you will new to open up the console while you run this in the simulator to see the results.



Finally the forth line returns YES, this will allow the UIWebView to follow the link, if you would just like to catch a link and stop the UIWebView from following it then simply return NO.



UIBUtton title image 不能同時顯示



[ leftbutton setTitle:_(@"About") forState:UIControlStateNormal ];





[ leftbutton setImage:image forState:UIControlStateNormal ];



不能同時顯示。



其他控制元件如:UINavigatonItem



不要在語言包裡面設定空格

有時,為了介面的需要,我們不要在語言包裡面加空格,要在程式中進行控制。

buttonTitle = [ NSString stringWithFormat:@"        %@", _(@"updateWeb") ];



NSNotificationCenter 帶引數傳送



MPMoviePlayerController* theMovie = [[MPMoviePlayerController alloc]initWithContentURL:[NSURL fileURLWithPath:[[[tableTitles objectForKey:keyIndex] objectAtIndex:row] objectAtIndex:3] ]];



[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMovieFinishedCallback:) name:MPMoviePlayerPlaybackDidFinishNotification object:theMovie];



[theMovie play];



-(void)myMovieFinishedCallback:(NSNotification*)aNotification



{



     MPMoviePlayerController *theMovie = [aNotification object];



   [[NSNotificationCenter defaultCenter] removeObserver:self           name:MPMoviePlayerPlaybackDidFinishNotification object:theMovie];



   // Release the movie instance [theMovie release];



}



------------



MPMoviePlayerController* theMovie = [[MPMoviePlayerController alloc]initWithContentURL:[NSURL fileURLWithPath:[[[tableTitles objectForKey:keyIndex] objectAtIndex:row] objectAtIndex:3] ]];



[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMovieFinishedCallback:) name:MPMoviePlayerPlaybackDidFinishNotification object:theMovie userInfo:dic];



[theMovie play];



-(void)myMovieFinishedCallback:(NSNotification*)aNotification



{



MPMoviePlayerController *theMovie = [aNotification object];



[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:theMovie];



// Release the movie instance [theMovie release];



}



延時一段時間執行某一函式



[self performSelector:@selector(dismissModal) withObject:self afterDelay:1.0];



無99美金證照聯機開發

第一步:進入 cd /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.1.sdk/ sudo vi SDKSettings.plist,將CODE_SIGNING_REQUIRED的值改成NO. 儲存後退出.



第二步:重新啟動XCode專案.



第三步:右擊專案GetInfo.將Code Signing下的Code Signing Identity值設定成Don`t Code Sign, 將Code Signing Identity下的Any iOS Device的值設定成空.



獲取IOS裝置的基本資訊

系統唯一標識

是什麼裝置:iPad還是iPhone等

iOS版本號

系統名稱



[[UIDevice currentDevice] uniqueIdentifier],

                       [[UIDevice currentDevice] localizedModel],

                       [[UIDevice currentDevice] systemVersion],

                       [[UIDevice currentDevice] systemName],

                       [[UIDevice currentDevice] model]];



用NSDateFormatter調整時間格式的程式碼



在開發iOS程式時,有時候需要將時間格式調整成自己希望的格式,這個時候我們可以用NSDateFormatter類來處理。

例如:



//例項化一個NSDateFormatter物件



NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];



//設定時間格式,這裡可以設定成自己需要的格式



[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];



//用[NSDate date]可以獲取系統當前時間



NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];



//輸出格式為:2010-10-27 10:22:13



NSLog(@”%@”,currentDateStr);



//alloc後對不使用的物件別忘了release



[dateFormatter release];



UIView設定成圓角方法



m_mainImgView.layer.cornerRadius = 6;

m_mainImgView.layer.masksToBounds = YES;



iPhone裡的frame和bounds區別






Objective-C記憶體管理



在使用Objective-C的工作中記憶體管理是首先要學會的一項技能,是如此重要,就好比是男人就要追漂亮姑娘一樣~~下面就來聊聊Apple官網上的記憶體管理的事情。



Objective-C的物件記憶體管理是一件非常有意思的事情,由其是在iPhone嵌入式裝置中.



想玩的省心點,就得熟知它的管理規則,由其是記憶體的管理機制。瞭解它的品性了才能在Cocoa的世界裡如魚得水。否則,反之(如水得魚!!^_^)。



首先,要牢記Apple的官網上的記憶體管理三定律:



1,一個物件可以有一個或多個擁有者



2,當它一個擁有都都沒有時,它就會被回收



3,如果想保留一個物件不被回收,你就必需成為它的擁有者





所有記憶體管理的原則全在這裡!!



簡單??哈哈!



名人曰:“大道至簡”



這兒玩意兒說起來比過家家還容易,但其實有些事情真正做起來並不是簡單的事兒~~



我們們首先來說怎麼樣才能成為一個物件的擁有者。Cocoa提供了一個機制叫"reference counting",翻譯過來就是“關聯記數器”(自己翻譯的,真不知叫啥,如果有官方的翻譯請通知我)。每一個物件都有一個關聯記數的值。當它被建立時,它的值為“1”。當值減少到“0”時,就會被回收(呼叫它的deallocate方法,如果沒有寫,則呼叫從NSObject繼承而來的回收方法,下文有說,一定要重寫該方法)。以下幾個方法可以操作這個記數:



1,alloc

   為物件分配記憶體,記數設為“1”,並返回此物件。



2,copy

   複製一個物件,此物件記數為“1”,返回此物件。你將成為此克隆物件的擁有者



3,retain

   物件“關聯記數”加“1”,併成為此物件的擁有者。



4,release

   物件“關聯記數”減“1”,並丟掉此物件。



5,autorelease



   在未來的某一時刻,物件“關聯記數”減“1”。並在未來的某個時間放棄此物件。



有了上面的幾個方法(當然這也是所有的記憶體操作的方法,簡單吧,哈哈哈)你就可以隨意操作一個物件的記數。並部分或完全的控制它的生命週期。但實際應用中,隨意亂寫上面的任何一個方法都可能會帶來嚴重的記憶體洩露。混亂的記憶體分配等於沒完沒了的麻煩工作,你不想在情人節的日子還在為記數之類的鳥問題而丟了老婆吧~~哈哈哈,為了美麗溫柔賢惠又善解人意的準老婆請牢記以下四條:



1,一個程式碼塊內要確保copy, alloc 和 retain 的使用數量與 release 和 autorelease 的數量。



2,在使用以“alloc”或“new”開頭或包含“copy”的方法,或“retain”一個物件時,你就會變為它的擁有者。



3,實現“dealloc”方法,並施放所有的例項變數。(其實這裡還有很多的巧兒門!!)



4,永不自己呼叫“dealloc”方法,這是系統當“retain”減到“0”時,自動呼叫的。手動呼叫會引起retain count記數錯誤(多一次的release)。



其實做到這些也不難,



retain count 增加與減少的方法對應,板丁板做到了就行了。



來自:http://blog.csdn.net/dboylx/archive/2009/02/13/3888746.aspx



iphone更改鍵盤右下角按鍵的type



以UISearchBar為例。





建立mySearchBar:



mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0, 0,320, SEARCH_HEIGHT)];

mySearchBar.placeholder = curPath;

[mySearchBar setDelegate:self];

//tableView.tableHeaderView =mySearchBar;

[self.view addSubview:mySearchBar];





更改按鍵的keyType(預設是return,這裡將它更改成done,當然還可以更改成其他的):

UITextField *searchField = [[mySearchBar subviews] lastObject];

[searchField setReturnKeyType:UIReturnKeyDone];

[mySearchBar release];

相關文章