Some Tips In Object C

本文深入探讨了Objective-C编程中的关键概念和技术,包括类、属性、消息传递、泛型等核心元素。同时,提供了从NSString到NSData的转换、日期时间操作、线程管理、错误处理、字符串替换等实用编程技巧。文章还展示了如何实现短信、邮件和电话功能,并通过代码实例详细解释了这些功能的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.使用class获得meta class

NSLog(@"Class name: %@",[[[arr objectAtIndex:i] class] description]);

2.使用NSClassFromString和 NSSelectorFromString

id object=[[NSClassFromString(@"NameofClass") alloc] init];//NSClassFromString加载的类不需要importSEL sel = NSSelectorFromString(@"doSomethingMethod:")//注意这个冒号,说明方法带有参数

if([object respondsToSelector:sel]) { 

    [object performSelector:sel withObject:color]; //注意如果有两个参数,使用两个withObject:参数;

3.使用isa

id movie=[arrFavorite objectAtIndex:row];

if (movie->isa ==[IndexPageItem class]) {

NSLog(@"movie title:%@",[movie description]);

}

4.谓词

NSArray* arr=[NSArray arrayWithObjects:@"1",@"0",@"no",@"NO",@"YES",@"yes",nil];

NSPredicate* predicate=[NSPredicate predicateWithFormat:

@"SELF IN{'0','no','NO'}"];

NSArray* result=[arr filteredArrayUsingPredicate:predicate];

NSLog(@"%@",result);

for (NSString* s in arr){

NSLog(@"%@:%d",s,[predicate evaluateWithObject:s]);

}

5. From NSString to NSData

NSString *text = @"Some string";

NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];

 

6. From NSData to NSString

NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

 

7.日期和时间

NSCalendar *gregorian=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponentstodayComponents=[gregorian components:(NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit) yourDate]; 

NSInteger theDay =[todayComponents day];

NSInteger theMonth =[todayComponents month]; 

NSInteger theYear =[todayComponents year]; 

// now build a NSDate object for yourDate using these components 

NSDateComponents *components =[[NSDateComponents alloc] init]; 

[components setDay:theDay];    

[components setMonth:theMonth];    

[components setYear:theYear];    

NSDate *thisDate =[gregorian dateFromComponents:components]; 

[components release];    

// now build a NSDate object for the next day    

NSDateComponents *offsetComponents =[[NSDateComponents alloc] init];  

[offsetComponents setDay:1]; 

NSDate *nextDate =[gregorian dateByAddingComponents:offsetComponents toDate: yourDate options:0];    

[offsetComponents release];    

[gregorian release];

8.使用performSelectorInBackground(多线程)调用的方法,必须在该方法中用NSAutoreleasePool

否则出现错误:no pool in place - just leaking。如果用performSelector则没有这个问题。

 

9.ld: symbol(s) not found 错误的解决办法

展开"Targets-->Compile Sources",查看列出的所有.m文件,找出其中缺失的.m文件,拖到其中。

 

10.Ojbect C让线程休眠

[NSThread sleepForTimeInterval:2];//单位是秒

 

11.nil和NULL的区别

在Object C中,NULL和nil都是空指针,不同的是,NULL用于c 指针,即(void *);而nil用于c++或java对象,即id为空


12.字符串替换

str=[str stringByReplacingOccurrencesOfString:@"[]" withString:@""];


13.assign,copy,retain之间的区别

  • assign: 简单赋值,不更改索引计数(Reference Counting)。
  • copy: 建立一个索引计数为1的对象,然后释放旧对象
  • retain:释放旧的对象,将旧对象的值赋予输入对象,再提高输入对象的索引计数为1

retain的实际语法为:

- (void)setName:(NSString *)newName {

if (name != newName) {

[name release];

name = [newName retain];

// name’s retain count has been bumped up by 1

}

}

说了那么麻烦,其实接下来的话最重要:

?如果你不懂怎么使用他们,那么就这样 ->

  • 使用assign: 对基础数据类型 (NSInteger,CGFloat)和C数据类型(int, float, double, char, 等等)
  • 使用copy: 对NSString
  • 使用retain: 对其他NSObject和其子类

14.nonatomic关键字:

atomic是Objc使用的一种线程保护技术,基本上来讲,是防止在写未完成的时候被另外一个线程读取,造成数据错误。而这种机制是耗费系统资源的,所以在iPhone这种小型设备上,如果没有使用多线程间的通讯编程,那么nonatomic是一个非常好的选择。

 

15.发送短信/邮件/打电话


+ (void)alert:(NSString *)msg
{
    UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:msg message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] autorelease];
    [alertView showWithBackground];
}

+ (NSString*) cleanPhoneNumber:(NSString*)phoneNumber
{
    NSString* number = [NSString stringWithString:phoneNumber];
    NSString* number1 = [[[number stringByReplacingOccurrencesOfString:@" " withString:@""]
                          //                        stringByReplacingOccurrencesOfString:@"-" withString:@""]
                          stringByReplacingOccurrencesOfString:@"(" withString:@""] 
                         stringByReplacingOccurrencesOfString:@")" withString:@""];
    
    return number1;    
}

+ (void) makeCall:(NSString *)phoneNumber
{
    if ([DeviceDetection isIPodTouch]){
        [UIUtils alert:kCallNotSupportOnIPod];
        return;
    }
    
    NSString* numberAfterClear = [UIUtils cleanPhoneNumber:phoneNumber];    
    
    NSURL *phoneNumberURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@", numberAfterClear]];
    NSLog(@"make call, URL=%@", phoneNumberURL);
    
    [[UIApplication sharedApplication] openURL:phoneNumberURL];    
}

+ (void) sendSms:(NSString *)phoneNumber
{
    if ([DeviceDetection isIPodTouch]){
        [UIUtils alert:kSmsNotSupportOnIPod];
        return;
    }
    
    NSString* numberAfterClear = [UIUtils cleanPhoneNumber:phoneNumber];
    
    NSURL *phoneNumberURL = [NSURL URLWithString:[NSString stringWithFormat:@"sms:%@", numberAfterClear]];
    NSLog(@"send sms, URL=%@", phoneNumberURL);
    [[UIApplication sharedApplication] openURL:phoneNumberURL];    
}

+ (void) sendEmail:(NSString *)phoneNumber
{
    NSURL *phoneNumberURL = [NSURL URLWithString:[NSString stringWithFormat:@"mailto:%@", phoneNumber]];
    NSLog(@"send sms, URL=%@", phoneNumberURL);
    [[UIApplication sharedApplication] openURL:phoneNumberURL];    
}

+ (void) sendEmail:(NSString *)to cc:(NSString*)cc subject:(NSString*)subject body:(NSString*)body
{
    NSString* str = [NSString stringWithFormat:@"mailto:%@?cc=%@&subject=%@&body=%@",
                     to, cc, subject, body];

    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    
}
16.NSString转换编码gb2312
NSURL *url=[NSURL URLWithString:urlStr];
NSData *data=[NSData dataWithContentsOfURL:url]NSStringEncoding enc=CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)NSString *retStr=[[NSString alloc]initWithData:data encoding:enc];

17.将指定格式的字符串转换为日期类型
//把yyyyMMddHHmmss格式的字符串转换为NSDate类型
-(NSDate*)stringToDate:(NSString*)dateString{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
NSDate *date = [dateFormatter dateFromString:dateString];
[dateFormatter release];
return date;}
18."Array was mutated while being enumerated"问题的解决
在操作数组对象时进行同步,如:@synchronized(enemiesArray) {
⋯⋯
数组操作代码
⋯⋯}
19、字符串与数组之间的转换:SString *string=@"one:two:three:four"; NSArray *result=[string componentsSeparatedByString:@":"]; string=[result componentsJoinedByString:@"_"]; 20、定时器NSTimer//1秒后,触发定时器事件
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFired) userInfo:nil repeats:NO]; 21、让UITextField里面的text垂直居中可以这样写: text.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; 22、在UITextField最右侧加图片是以下代码,     UIImageView *imgv=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"right.png"]];     text.rightView=imgv;     text.rightViewMode = UITextFieldViewModeAlways;    如果是在最左侧加图片就换成: text.leftView=imgv; text.leftViewMode = UITextFieldViewModeAlways; 23、NSLog 的格式化字符串 %@ 对象 %% 百分号 %d, %i 整数 %u 无符整形 %f 浮点/双字 %x, %X 二进制整数 %o 八进制整数 %zu size_t %p 指针 %e 浮点/双字 (科学计算) %g 浮点/双字 %s C 字符串 %.*s Pascal字符串 %c 字符 %C unichar %lld 64位长整数(long long) %llu 无符64位长整数 %Lf 64位双字
24、直接链接到itunes

NSURL *url = [NSURL URLWithString:@"itms-apps://itunes.apple.com/us/album/esperanza/id321585893"];

        [[UIApplication sharedApplication] openURL:url];

直接链接到safari网页

 [[UIApplication sharedApplication] openURL:[NSURLURLWithString:@"http://www.google.com"]];

25、获取Bundle的版本号

NSString* localVersion= [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];

26、stray '\357' in program

错把'['写成中文的方括号'['了。

27、provisioning profile 'xxx' can't be found

如果你更新了profile,再编译iphone项目,发现下面的错误,那你无论如何clean也不会成功,那真是让人恼火阿

这时候,先copy上面那行出错信息中的profile identifier,比如:86C90BA7-77B6-4A75-9EAD-A1FD88C17F6D

然后关闭这个项目,打开finder到你的项目文件xxxx.xcodeproj上面按鼠标右键,选择Show Package Contents菜单。

在新打开的finder的,找到project.pbxproj,使用一个文本edit打开它,用查找功能找到所有的有那行编码的位置,删除那一行:

"PROVISIONING_PROFILE[sdk=iphoneos*]" = "86C90BA7-77B6-4A75-9EAD-A1FD88C17F6D";

删除以后,保存这个 project.pbxproj 文件,用xcode重新打开你的项目,再编译一下试试

转自:http://blog.youkuaiyun.com/kmyhy/article/details/5716755

<think>我们正在处理一个在Python 3.8环境中导入NumPy时出现的ImportError,错误信息提示缺少libcblas.so.3。这个问题通常是因为系统缺少必要的BLAS(Basic Linear Algebra Subprograms)库,或者NumPy无法找到这些库。 根据引用[3]的内容,我们了解到在搭建Python环境时可能会遇到动态库缺失的问题,例如`libcudart.so.11.0`和`libnvinfer.so.7`,而解决这类问题的方法通常是安装对应的库或创建符号链接。但这里缺失的是`libcblas.so.3`,它是BLAS库的一部分。 解决方案通常包括: 1. 安装包含该库的软件包(例如,在Ubuntu/Debian上安装libatlas-base-dev或libopenblas-dev)。 2. 检查库的路径是否在系统的库搜索路径中,如果没有,可以添加路径或创建符号链接。 由于用户使用的是Python 3.8,并且通过错误信息可以知道是动态库的问题,我们可以按照以下步骤来解决: 步骤1:确认系统是否安装了BLAS库 在Ubuntu/Debian系统上,可以尝试安装libopenblas-dev(它提供了libcblas.so.3): ```bash sudo apt update sudo apt install libopenblas-dev ``` 步骤2:安装后,检查库文件是否存在 通常,安装后库文件会位于`/usr/lib`或`/usr/lib/x86_64-linux-gnu`等目录。我们可以使用以下命令查找: ```bash sudo find / -name 'libcblas.so.3' 2>/dev/null ``` 步骤3:如果库文件存在,但NumPy仍然找不到,可能是因为路径不在环境变量LD_LIBRARY_PATH中。可以临时添加路径: ```bash export LD_LIBRARY_PATH=/path/to/library:$LD_LIBRARY_PATH ``` 或者永久添加,将上述命令添加到~/.bashrc或~/.profile中。 步骤4:如果上述方法无效,可以考虑创建符号链接到系统库目录(如果库文件在其他位置): ```bash sudo ln -s /path/to/found/libcblas.so.3 /usr/lib/ ``` 步骤5:重新安装NumPy以确保它能够正确链接到库: ```bash pip uninstall numpy pip install numpy ``` 另外,根据引用[4],虽然它主要讲的是NumPy处理缺失值,但我们可以知道NumPy依赖于底层线性代数库,因此确保这些库的完整性非常重要。 注意:如果用户是在虚拟环境中使用,那么系统级的库安装仍然是必要的,因为NumPy的底层依赖是系统级的。 如果用户使用的是其他Linux发行版,安装命令可能不同(例如,CentOS上可能是`yum install openblas-devel`)。 如果问题仍然存在,可能需要检查NumPy的构建选项,或者考虑使用预编译的NumPy轮子(wheel)文件,这些轮子文件通常已经包含了必要的BLAS实现(如OpenBLAS)。但是,如果系统缺少依赖,预编译的轮子也可能无法运行。 由于用户的环境是Python 3.8,我们可以确认NumPy从1.19.4版本开始提供了许多Linux平台的轮子文件,这些轮子文件是使用OpenBLAS构建的,因此安装时应该不需要系统有BLAS库。但是,如果用户安装的NumPy是从源代码构建的,那么就需要系统有BLAS库。 因此,另一个解决方案是使用预编译的轮子重新安装NumPy: ```bash pip uninstall numpy pip install numpy --only-binary=:all: ``` 这样会强制pip安装预编译的轮子,而不是从源代码构建。 最后,如果用户是在Windows或macOS上遇到此问题,那么解决方案会不同。但根据错误信息(`libcblas.so.3`)可以判断是Linux系统。 总结步骤: 1. 安装libopenblas-dev(或对应系统的BLAS开发包)。 2. 确保库文件可以被找到(通过LD_LIBRARY_PATH或符号链接)。 3. 重新安装NumPy(使用预编译轮子)。 下面我们按照要求生成相关问题。</think>### 解决 Python 3.8 中导入 NumPy 时缺少 `libcblas.so.3` 的错误 此问题是由于系统缺少 **BLAS(基础线性代数子程序)库** 或环境配置不当导致的。以下是详细解决方案: --- #### 解决方法 1. **安装 BLAS 依赖库** 在终端执行以下命令安装 OpenBLAS(提供 `libcblas.so.3`): ```bash # Ubuntu/Debian 系统 sudo apt update sudo apt install libopenblas-dev # CentOS/RHEL 系统 sudo yum install openblas-devel ``` 2. **验证库文件路径** 安装后检查库文件是否存在: ```bash # 查找库文件位置 sudo find / -name 'libcblas.so.3' 2>/dev/null # 典型路径示例 /usr/lib/x86_64-linux-gnu/libcblas.so.3 ``` 3. **添加库路径到系统配置** 若库文件不在默认路径,需手动添加路径: ```bash # 临时生效(当前终端) export LD_LIBRARY_PATH=/your/library/path:$LD_LIBRARY_PATH # 永久生效(添加到 ~/.bashrc 或 /etc/environment) echo 'export LD_LIBRARY_PATH=/your/library/path:$LD_LIBRARY_PATH' >> ~/.bashrc source ~/.bashrc ``` 4. **重建 NumPy 链接** 重新安装 NumPy 确保正确链接: ```bash pip uninstall -y numpy pip install --no-cache-dir numpy ``` 5. **检查虚拟环境配置** 若使用虚拟环境(如 Conda),需确保系统库可被访问: ```bash # 激活环境后验证链接 conda activate your_env ldd $(python -c "import numpy as np; print(np.__file__)") | grep cblas ``` 应显示类似输出:`libcblas.so.3 => /usr/lib/x86_64-linux-gnu/libcblas.so.3` --- #### 根本原因分析 - NumPy 依赖 BLAS 库加速线性代数运算,缺失 `libcblas.so.3` 会导致导入失败[^3][^4]。 - Python 3.8 的虚拟环境可能未正确继承系统库路径,尤其从源码编译 NumPy 时[^5]。 - 系统升级或部分卸载操作可能导致库文件丢失。 --- #### 验证修复 运行 Python 检查导入是否成功: ```python import numpy as np print(np.__version__) # 应输出版本号(如 1.24.3) ``` --- #### 扩展建议 - **兼容性检查**:确认 NumPy 版本支持 Python 3.8(推荐 ≥1.19.0)[^5]。 - **Docker 方案**:使用官方镜像避免环境问题: ```Dockerfile FROM python:3.8-slim RUN apt update && apt install -y libopenblas-dev RUN pip install numpy ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值