(转载)ios开发知识总结 — 下

三:使用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:@"\n"];



         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];
相关文章
相关标签/搜索