iphone知识汇总

来源:互联网 发布:知乎电力系统仿真书籍 编辑:程序博客网 时间:2024/06/01 09:34

 iPhone上读取ansi字符串的例子   

 

 

iPhoneNSString并不支持ansi的字符串(比如咱们常用的gb2312), 因此如果要读取的话需要转换为UTF-8

iPhone上自带了libiconv于是这个转换变的就比较简单了

 

首先在工程的Framework部分加入/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.0.sdk/usr/lib/libiconv.dylib

当然中间那个iPhoneOS3.0.sdk需要换成你当前使用的SDK版本

 

实际转换过程也就4.

1, 引入iconv库并添加头文件

2, 利用iconv_open设置fromto的字符串编码

3, 执行iconv进行转换

4, 利用iconv_close关闭iconv_open创建的实例.

 

基本上就是下面的代码片段中 code_convert中的逻辑了.

 

 

#include <iconv.h>

 

int code_convert(char *from_charset, char *to_charset, char *inbuf, size_t inlen, char *outbuf, size_t outlen) {

    iconv_t cd = NULL;

 

    cd = iconv_open(to_charset, from_charset);

    if(!cd)

        return -1;

 

    memset(outbuf, 0, outlen);

    if(iconv(cd, &inbuf, &inlen, &outbuf, &outlen) == -1)

        return -1;

 

    iconv_close(cd);

    return 0;

}

 

int u2g(char *inbuf, size_t inlen, char *outbuf, size_t outlen) {

    return code_convert("utf-8""gb2312", inbuf, inlen, outbuf, outlen);

}

 

int g2u(char *inbuf, size_t inlen, char *outbuf,size_t outlen) {

    return code_convert("gb2312""utf-8", inbuf, inlen, outbuf, outlen);

}

 

 

 

而在实际应用时无论从文件或者网络读取都要获取成NSData或者char *void *, 至少不能是NSString, 因为NSString无法直接处理.

以获取成NSData为例.

 

 

 

(NSString *)getANSIString:(NSData *)ansiData {

    char *ansiString = [ansiData bytes];

    int ansiLen = [ansiData length];

    int utf8Len = ansiLen * 2//其实*1.5基本就够了

    char *utf8String = (char *)malloc(utf8Len);

    memset(utf8String0, utf8Len)//虽然code_convert中也memset但还是自己分配后就set一次比较好

    int result = code_convert("gb2312""utf-8", ansiString, ansiLen, utf8String, utf8Len);

    if(result == -1) {

        free(utf8String);

        return nil;

    }

    NSString *retString = [NSString stringWithUTF8String:utf8String];

    free(utf8String);

    return retString;

}

 



代码并未实际跑过不过逻辑上应该没有问题 (其实转换部分是抄的)
例子工程嘛就算了吧.

自动调整UILabel的高度

 

 

UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0000)];

// 这个大小可以随便写,反正后面会改变他

 

label.backgroundColor = [UIColor redColor];

label.font = [UIFont systemFontOfSize:40];//这个也随便设任何字体都会自动计算出 合适的大小

label.text = @"1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz";

//label.text = @"1234";

 

label.numberOfLines = 0;//这个一定要设成0

 

CGSize ssize = [label sizeThatFits:CGSizeMake(1000)];

/*这个的意思是,我希望我这个label的宽度是100, 而高度随着字符串的长增加

一定要注意自适应时是以适应width为基准的达到这个width就会接着改变height

也就是说如果你的字符串很长很长那么他会把width固定然后得到适合这个字符串的height

所以这里sizeheight我设成了0, 因为他肯定是要被改变的,

如果你的字符串很短达不到那个width, 这时会自动的得到适合这个字符串的width

*/

 

CGRect rct = label.frame;

rct.size = ssize;

label.frame = rct;

label.center = CGPointMake(160160);

 

使用NSStreams建立TCP鏈接 (iPhone OS不支持NSHost得情況下)   

 

 

暫時de地址將來可能會去掉url裡邊得prerelease

Technical Q&A QA1652Using NSStreams For A TCP Connection Without NSHost

 

Q: Given that +getStreamsToHost:port:inputStream:outputStream: is not supported on iPhone OS, how can I create NSStreams for a TCP connection to a named host?

A: You can do this by exploiting the toll-free bridge between NSStream and CFStream. Use CFStreamCreatePairWithSocketToHost to create CFStreams to the host, and then cast the resulting CFStreams to NSStreams.

 

Listing 1 shows an example of this. It adds a category to NSStream that implements a replacement for +getStreamsToHost:port:inputStream:outputStream:.

 

Listing 1: A category to creates TCP streams to a named host

 

 

 

@interface NSStream (MyAdditions)

 

(void)getStreamsToHostNamed:(NSString *)hostName 

    port:(NSInteger)port 

    inputStream:(NSInputStream **)inputStreamPtr 

    outputStream:(NSOutputStream **)outputStreamPtr;

 

@end

 

@implementation NSStream (MyAdditions)

 

(void)getStreamsToHostNamed:(NSString *)hostName 

    port:(NSInteger)port 

    inputStream:(NSInputStream **)inputStreamPtr 

    outputStream:(NSOutputStream **)outputStreamPtr

{

    CFReadStreamRef     readStream;

    CFWriteStreamRef    writeStream;

 

    assert(hostName != nil);

    assert( (port > 0) && (port < 65536) );

    assert( (inputStreamPtr != NULL) || (outputStreamPtr != NULL) );

 

    readStream = NULL;

    writeStream = NULL;

 

    CFStreamCreatePairWithSocketToHost(

        NULL

        (CFStringRef) hostName

        port

        ((inputStreamPtr  != nil) ? &readStream : NULL),

        ((outputStreamPtr != nil) ? &writeStream : NULL)

    );

 

    if (inputStreamPtr != NULL) {

        *inputStreamPtr  = [NSMakeCollectable(readStream) autorelease];

    }

    if (outputStreamPtr != NULL) {

        *outputStreamPtr = [NSMakeCollectable(writeStream) autorelease];

    }

}

 

@end

 

iPhone类代码]保存数据:多个对象   

 

 

存:

[[NSArray arrayWithObjects:playername,GameSavedata,nil] writeToFile:self.saveScorefile atomically:NO];

 

 

取:

NSArray *datapaths = NSSearchPathForDirectoriesInDomains(

                                                             NSDocumentDirectory, 

                                                             NSUserDomainMask, 

                                                             YES);

    

    

    self.saveScorefile=[NSString stringWithFormat: @"%@/scoredata.plist", [datapaths objectAtIndex:0]];

    if([[NSFileManager defaultManager] fileExistsAtPath:saveScorefile])

        self.datascorearray=[NSMutableArray arrayWithContentsOfFile:saveScorefile];        

    else

        self.datascorearray=[ NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle]  pathForResource:@"scoredata" ofType:@"plist"]];

    

    self.playername=[self.datascorearray objectAtIndex:0];

    self.GameSavedata=[self.datascorearray objectAtIndex:1];

 

 

每次点击UITextView输入文本都从头开始的代码   

 

 

原理很简单 实现一个UITextView的协议 用这个代码可以实现每次开始输入光标都从最初点开始的效果

 

 

 

(void)textViewDidChangeSelection:(UITextView *)textView

{

    NSRange range;

    range.location = 0;

    range.length  = 0;

    textView.selectedRange = range;

}

 

 

Matrix Digital Raining 動畫效果   

 

 

cocos2d 作成的 Matrix Digital Raining 動畫效果 

.h 

 

 

#define GRADIENT     10

#define SCREENWIDTH  480

#define SCREENHEIGHT 360

#define FONTSIZE     10

#define FONTSPACE    1

#define CHARROW      (SCREENHEIGHT / FONTSIZE)

#define CHARCOLUMN   (SCREENWIDTH / FONTSIZE)

 

 

@interface background : CCLayer

{

            CCTimer *timer;

            NSString *msg;

            int length;

            ccColor3B colorList[GRADIENT];

            CCBitmapFontAtlas *fontArray[CHARCOLUMN][CHARROW];

            int drop[CHARROW];

}

 

@end

 

 

 

.m 

 

 

@implementation background

(id)init

{

        self = [super init];

        if (self != nil)

        {

                msg = @"abcdefghijklmnopqestuvwxyzABCDEFGHJIKLMNOPQRSTUVWXYZ1234567890";

 

                length = [msg length];

                colorList[0] = ccc3(000);

                // Initial the color gradient

                for (int i = 1; i < GRADIENT; ++i)

                        colorList[i] = ccc3(0255-20*i, 0);

 

                for (int i = 0; i < CHARCOLUMN; ++i)

                {

                        for (int j = 0; j < CHARROW; ++j)

                        {

                                fontArray[i][j] = [CCBitmapFontAtlas bitmapFontAtlasWithString:[msg substringWithRange:NSMakeRange(rand()%length1)] fntFile:@"matrixFont.fnt"];

                                fontArray[i][j].position = *****(SCREENWIDTH - i * FONTSIZE, SCREENHEIGHT- j * FONTSIZE);

                                fontArray[i][j].color = colorList[0];

                                [self addChild:fontArray[i][j]];

                        }

                        drop[i] = (rand() % CHARCOLUMN);

                }

        }

        return self;

}

 

 

(void) onEnter

{

        [super onEnter];

        timer = [CCTimer timerWithTarget:self selector:@selector(updateBackgroundAnimation:) interval:.1];

        [[CCScheduler sharedScheduler] scheduleTimer:timer];

}

 

(void) onExit

{

        [[CCScheduler sharedScheduler] unscheduleTimer:timer];

        [super onExit];

}

 

(void) updateBackgroundAnimation:(id) sender

{

        for (int x = 0; x < CHARCOLUMN; ++x)

        {

                for (int y = 0y < drop[x]; ++y)

                {

                        if (drop[x] - y <= GRADIENT)

                        {

                                fontArray[x][y%CHARROW].color = colorList[drop[x]-y-1];

                        }

                        else

                                fontArray[x][y%CHARROW].color = colorList[0];

                }

                if (drop[x] < (CHARROW + GRADIENT))

                        drop[x]++;

                else

                        drop[x] = 0;

        }

}

 

@end

 

 

自己写的 char* 加入到TextViewmethod   

 

 

大家可能用得到吧....

AAA.h:

IBOutlet NSTextView * mytextview;

 

 

AAA.m

 

-(void)TextViewProcess:(char *)Text TextColor:(NSColor *)Color //color don't work now

{

NSString *TextString;

NSRange range;

 

//NSLog(@"%s",Text);

TextString=[NSString stringWithFormat:@"%s",Text]; 

[[[mytextview textStoragemutableStringappendString:TextString];// add text 

 

range = NSMakeRange([[[Showinfo textStoragemutableString]length],0); 

[mytextview scrollRangeToVisible:range]; //move to end of textview

}

原创粉丝点击