Some Tips In Object C

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

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

基于STM32 F4的永磁同步电机无位置传感器控制策略研究内容概要:本文围绕基于STM32 F4的永磁同步电机(PMSM)无位置传感器控制策略展开研究,重点探讨在不依赖物理位置传感器的情况下,如何通过算法实现对电机转子位置和速度的精确估计与控制。文中结合嵌入式开发平台STM32 F4,采用如滑模观测器、扩展卡尔曼滤波或高频注入法等先进观测技术,实现对电机反电动势或磁链的估算,进而完成无传感器矢量控制(FOC)。同时,研究涵盖系统建模、控制算法设计、仿真验证(可能使用Simulink)以及在STM32硬件平台上的代码实现与调试,旨在提高电机控制系统的可靠性、降低成本并增强环境适应性。; 适合人群:具备一定电力电子、自动控制理论基础和嵌入式开发经验的电气工程、自动化及相关专业的研究生、科研人员及从事电机驱动开发的工程师。; 使用场景及目标:①掌握永磁同步电机无位置传感器控制的核心原理与实现方法;②学习如何在STM32平台上进行电机控制算法的移植与优化;③为开发高性能、低成本的电机驱动系统提供技术参考与实践指导。; 阅读建议:建议读者结合文中提到的控制理论、仿真模型与实际代码实现进行系统学习,有条件者应在实验平台上进行验证,重点关注观测器设计、参数整定及系统稳定性分析等关键环节。
> date='250507' > library(Matrix) > library(matrixStats) > library(Seurat) 载入需要的程辑包:SeuratObject 载入需要的程辑包:sp 载入程辑包:‘SeuratObject’ The following objects are masked from ‘package:base’: intersect, t > library(dplyr) 载入程辑包:‘dplyr’ The following object is masked from ‘package:matrixStats’: count The following objects are masked from ‘package:stats’: filter, lag The following objects are masked from ‘package:base’: intersect, setdiff, setequal, union > library(reshape2) > library(ape) 载入程辑包:‘ape’ The following object is masked from ‘package:dplyr’: where > # install.packages("writexl") > library(writexl) > > > date='250507' > filePrefix <- paste0(date, "_MLB018.") > figDir <- "D:/software/RStudio/projects/PBNscRNAseq/figs" > objectDir <- "D:/software/RStudio/projects/PBNscRNAseq/objects" > > # read objects > object <- readRDS(paste0(objectDir, "/diet/sct/", date, "_MLB018.subs.dbl.sct.int.pca.umap.neighbors25.minDist0.4.spread0.6.k25.res0.04.diet.sct.full.rds")) > filestring <- substr(sapply(strsplit(list.files(paste0(objectDir, "/diet/sct"), pattern="*.rds", full.names=T), "MLB018."), tail, 1), 0, nchar(sapply(strsplit(list.files(paste0(objectDir, "/diet/sct"), pattern="*.rds", full.names=T), "MLB018."), tail, 1))-4) > commGenes <- rownames(object[["SCT"]]@scale.data) > > # 修正SCT模型设置 > for(model in names(object@assays$SCT@SCTModel.list)) { + object@assays$SCT@SCTModel.list[[model]]@umi.assay <- 'SCT' + } > > > object <- PrepSCTFindMarkers(object, assay = "SCT") Found 4 SCT models. Recorrecting SCT counts using minimum median counts: 2756 |++++++++++++++++++++++++++++++++++++++++++++++++++| 100% elapsed=01m 26s > markersClust.LRT.list <- list() > for (i in seq_along(unique(object@meta.data$tree.ident))){ + markersClust.LRT.list[[i]] <- FindMarkers( + object, + ident.1 = i, + slot = "scale.data", + features = commGenes, + logfc.threshold = 0, + test.use = "bimod", + min.pct = 0, # Minimum Percentage,表示基因必须在某个cluster中至少0%的细胞中表达 + min.diff.pct = 0, + only.pos = F, + verbose = T) + markersClust.LRT.list[[i]] <- cbind( + markersClust.LRT.list[[i]], + gene = rownames(markersClust.LRT.list[[i]]), + cluster = rep(i, nrow(markersClust.LRT.list[[i]])) + ) + } Warning: The following arguments are not used: norm.method |++++++++++++++++++++++++++++++++++++++++++++++++++| 100% elapsed=01m 03s Warning: The following arguments are not used: norm.method |++++++++++++++++++++++++++++++++++++++++++++++++++| 100% elapsed=01m 03s Warning: The following arguments are not used: norm.method |++++++++++++++++++++++++++++++++++++++++++++++++++| 100% elapsed=01m 04s Warning: The following arguments are not used: norm.method |++++++++++++++++++++++++++++++++++++++++++++++++++| 100% elapsed=01m 06s Warning: The following arguments are not used: norm.method |++++++++++++++++++++++++++++++++++++++++++++++++++| 100% elapsed=01m 05s Warning: The following arguments are not used: norm.method |++++++++++++++++++++++++++++++++++++++++++++++++++| 100% elapsed=01m 08s Warning: The following arguments are not used: norm.method |++++++++++++++++++++++++++++++++++++++++++++++++++| 100% elapsed=01m 08s > > # 检查某个cluster的top标记基因, 7为 neuron cluster > top_markers <- markersClust.LRT.list[[7]] %>% + arrange(p_val) %>% + head(10) > > # 查看这些基因的表达分布 > VlnPlot(object, features = top_markers$gene[1:3], layer = "data") > > markersClust.LRT.pVal.list <- lapply(markersClust.LRT.list, function(x) {x[c("gene", "p_val_adj")]}) > for (i in seq_along(markersClust.LRT.pVal.list)){colnames(markersClust.LRT.pVal.list[[i]]) <- c("gene", paste0("c",i, ".pVal"))} > markersClust.LRT.pVal <- Reduce(function(x,y)merge(x,y,by="gene", all = T), markersClust.LRT.pVal.list) > row.names(markersClust.LRT.pVal) <- markersClust.LRT.pVal[,1] > markersClust.LRT.pVal <- markersClust.LRT.pVal[,-1] > > saveRDS(markersClust.LRT.pVal, paste0(objectDir,"/markers/clusterMarkers/pval/",filePrefix,filestring,".clusterMarkers.LRT.low.rds")) > write.table(markersClust.LRT.pVal, paste0(objectDir,"/markers/clusterMarkers/pval/",filePrefix,filestring,".clusterMarkers.LRT.low.txt"), sep="\t", col.names=NA) > write_xlsx( + markersClust.LRT.pVal, + path = paste0(objectDir, "/markers/clusterMarkers/pval/", filePrefix, filestring, ".clusterMarkers.LRT.low.xlsx") + ) > > # find markersClust along tree siblings using LRT and create pVal matrix by cluster > tree <- Tool(object = object, slot = 'BuildClusterTree') > edges.tips <- as.data.frame(tree$edge) > edges.tips <- edges.tips[edges.tips$V2%in%as.integer(tree$tip.label),] Warning message: In edges.tips$V2 %in% as.integer(tree$tip.label) : 强制改变过程中产生了NA > colnames(edges.tips) <- c("edges", "tips") > > tips.list <- list() > for (i in seq_along(edges.tips$tips)){tips.list[[i]] <- as.numeric(extract.clade(tree, node = as.integer(edges.tips[i,1]))$tip.label)} > > markersClust.LRT.list <- list() > for (i in seq_along(unique(object@meta.data$tree.ident))){ + markersClust.LRT.list[[i]] <- FindMarkers(object, i, c(tips.list[[i]][!tips.list[[i]]%in%i]), slot = "scale.data", features = commGenes, logfc.threshold = 0, test.use = "bimod", min.pct = 0, min.diff.pct = 0, only.pos = F, verbose = T) + markersClust.LRT.list[[i]] <- cbind(markersClust.LRT.list[[i]], gene = rownames(markersClust.LRT.list[[i]]), cluster = rep(i, nrow(markersClust.LRT.list[[i]])))} Error in tips.list[[i]] : 下标出界 > print(edges.tips$tips) integer(0) > print(length(edges.tips$tips)) [1] 0 > > tips.list list() > length(tips.list) [1] 0 > print(tree$tip.label) [1] "g1" "g2" "g3" "g4" "g5" "g6" "g7" > print(length(tree$tip.label)) [1] 7 > > tree Phylogenetic tree with 7 tips and 6 internal nodes. Tip labels: g1, g2, g3, g4, g5, g6, ... Rooted; includes branch lengths. > tree$edge [,1] [,2] [1,] 8 1 [2,] 8 9 [3,] 9 2 [4,] 9 10 [5,] 10 3 [6,] 10 11 [7,] 11 4 [8,] 11 12 [9,] 12 5 [10,] 12 13 [11,] 13 6 [12,] 13 7 > edges.tips <- as.data.frame(tree$edge) > edges.tips <- edges.tips[edges.tips$V2%in%as.integer(tree$tip.label),] Warning message: In edges.tips$V2 %in% as.integer(tree$tip.label) : 强制改变过程中产生了NA > print(edges.tips) [1] V1 V2 <0 行> (或0-长度的row.names) > print(dim(edges.tips)) [1] 0 2 > print(tree$tip.label) [1] "g1" "g2" "g3" "g4" "g5" "g6" "g7" > print(which(is.na(tree$tip.label))) # 查看是否有 NA integer(0) > print(as.integer(tree$tip.label)) # 转换时是否报错 [1] NA NA NA NA NA NA NA Warning message: In print(as.integer(tree$tip.label)) : 强制改变过程中产生了NA
05-14
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值