[iOS]小问题记录



字符串的是连接object-c和c++的最重要元素,学好字符串的处理,就等于学好了oc和c++的混编


char * /const char *和NSString之间的转化


//char * /const char * 转NSString
NSString * strPath = [NSString stringWithUTF8String:filename];


//NSString转char * /const char * 
const char * filePathChar = [filePath UTF8String];
华丽的分割线//
转化char 到nsstring


char myChar = 'a';
NSString * string = [NSString stringWithFormat:@"%c", myChar];
提取NSString的某个字段到char
- (unichar)characterAtIndex:(NSUInteger)index;


华丽的分割线//


c++ 和 oc的本身是不能直接对接的。要通过c的api做连接的。
string 转 NSString
string str = [aNSString UTF8String];




NSString 转 string
string str("testStr");
NSString * aString = [NSString stringWithUTF8String:str.c_str()];


华丽的分割线//


1. NSString and std::string convert to each other

//from stackoverflow
//nsstring to string
NSString *strA = @"NSString";
std::string *strB = new std::string([strA UTF8String]);
//or
std::string strB([strA UTF8String]);
//string to nsstring
NSString *str = [NSString stringWithCString:string.c_str() 
                                   encoding:[NSString defaultCStringEncoding]];
NSString *str = [NSString stringWithCString:string.c_str() 
                                   encoding:NSUTF8StringEncoding]; // for chinese




std::string param; // <-- input
NSString* result = [NSString stringWithUTF8String:param.c_str()];
NSString* alternative = [[NSString alloc] initWithUTF8String:param.c_str()];
//chinese
[NSString stringWithCString:m_AnswerSheet.GetName().c_str()

                                                       encoding:NSUTF8StringEncoding]


2. how does NSString implement trimRight?this may help: link

//this removes white space from both ends of a string
NSString *newString = [oldString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

//just wanna remove white space at the end of the string? read the link above for more detail.


3. convert std::vector and NSArray to each other

std::vector<std::string> strVec;
for (int i = 0; i < [NSMutableArrayObject count]; i++) {
   NSString *NS_Ans = (NSString *)[NSMutableArrayObject objectAtIndex:i];
   std::string Str_Ans = *new std::string([NS_Ans UTF8String]);
   strVec.push_back(Str_Ans);
}
return strVec;
//
std::vector<std::string> ansArray = getOneVector();           
NSMutableArray *nsArray = [NSMutableArray array];
for (int j = 0; j < ansArray.size(); j++) {
   NSString *item = [NSString stringWithCString:ansArray[j].c_str() encoding:[NSString defaultCStringEncoding]];         
   [nsArray addObject:item];
}

return ansArray;  

          

4. NSString append

string = [NSString initWithFormat:@"%@,%@", string1, string2 ];
string = [string1 stringByAppendingString:string2];

string = [string stringByAppendingFormat:@"%@,%@",string1, string2];


5. Get uuid in cocoa .reference from 各种OS中生成UUID的方法

std::string CHelpFunction::stringWithUuid() {
    CFUUIDRef uuidObj = CFUUIDCreate(nil);
    NSString *uuidString = (NSString *)CFBridgingRelease(CFUUIDCreateString(nil, uuidObj));
    CFRelease(uuidObj);
    return [uuidString UTF8String];

}


6. set UIView background image

UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.png"]];

[myLabel setBackgroundColor:color];


7. set UIImage a click event, suitable for other uiview i think. reference

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];
singleTap.numberOfTapsRequired = 1;
[PReArrowImage setUserInteractionEnabled:YES];
[preArrowImage addGestureRecognizer:singleTap];


-(void)tapDetected{
    NSLog(@"single Tap on imageview");

  }


8. save int value in nsdictionary

[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:m_quesIndex] forKey:@"index"];
//get

i = [[dic objectForKey:@"index"] intValue];


9. NSNotification

//send
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
NSDictionary *d = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:m_index] forKey:@"index"];
[nc postNotificationName:@"viewClicked" object:self userInfo:d];
//regist observer
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewClickAt:) name:@"quesViewClicked" object:nil];
//do function
- (void)quesViewClickAt:(NSNotification *)noti {
    int index = [[[noti userInfo] objectForKey:@"index"] intValue];
}
//dealloc
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}


10. force close keyboard

[view endEditing:YES]; 


11. remove all subviews

NSArray *viewsToRemove = [self.view subviews];
for (UIView *v in viewsToRemove) {
    [v removeFromSuperview];
}

12. limit the input

- (BOOL)textView:(nonnull UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(nonnull NSString *)text {
    // Prevent crashing undo bug 
    if(range.length + range.location > textView.text.length)
    {
        return NO;
    }
    
    NSUInteger newLength = [textView.text length] + [text length] - range.length;
    return newLength <= 1024;

}


13. insert null object into NSMutableArray or NSMutableDictionary etc.

if ((NSNull *)[mPages objectAtIndex:showPos] == [NSNull null]) {
        [mPages removeObjectAtIndex:showPos];
}
[mPages insertObject:mPage atIndex:showPos];


[mPages removeObjectAtIndex:hidePos];

[mPages insertObject:[NSNull null] atIndex:hidePos];


14. UIScrollView scoll to top

UPDATE FOR iOS 7

[self.scrollView setContentOffset:
    CGPointMake(0, -self.scrollView.contentInset.top) animated:YES];
ORIGINAL


[self.scrollView setContentOffset:CGPointZero animated:YES];
or if you want to preserve the horizontal scroll position and just reset the vertical position:


[self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x, 0)

    animated:YES];


15. UITextField 增加输入框靠左边距 link

UITextField *content = ......;
//设置输入左边距
CGRect frame = content.frame;
frame.size.width = 5;
UIView *leftView = [[UIView alloc] initWithFrame:frame];
content.leftViewMode = UITextFieldViewModeAlways;

content.leftView = leftView;


16. 多个UITextField,键盘return 改为 next->next->done

//set keyboard
if (i == count - 1) 
   [contentText setReturnKeyType:UIReturnKeyDone];
else
   [contentText setReturnKeyType:UIReturnKeyNext];
#pragma mark - TextFieldDelegate
- (BOOL)textFieldShouldReturn:(nonnull UITextField *)textField {
    NSInteger nextTag = textField.tag + 1;
    // Try to find next responder
    UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
    if (nextResponder) {
        // Found next responder, so set it.
        [nextResponder becomeFirstResponder];
    } else {
        // Not found, so remove keyboard.
        [textField resignFirstResponder];
    }
    return NO; // We do not want UITextField to insert line-breaks.

}


17. ios系统号detect

#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)


if (SYSTEM_VERSION_LESS_THAN(@"8.0")) {
   ...

}


18. drawInRect: withAttributes:

UIFont *textFont = [UIFont fontWithName: @"Helvetica" size: 60];
UIColor *textColor = [UIColor blackColor];
NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
textStyle.lineBreakMode = NSLineBreakByWordWrapping;
textStyle.alignment = NSTextAlignmentCenter;
    
[textContent drawInRect:textRect withAttributes:@{NSFontAttributeName:textFont, NSForegroundColorAttributeName:textColor, NSParagraphStyleAttributeName:textStyle}];


19. 设置粗体文字

首先可以上这个网站:http://iosfonts.com/查看自己要用的字体是否支持粗体,然后使用下面方法


-(void)boldFontForLabel:(UILabel *)label{
    UIFont *currentFont = label.font;
    UIFont *newFont = [UIFont fontWithName:[NSString stringWithFormat:@"%@-Bold",currentFont.fontName] size:currentFont.pointSize];
    label.font = newFont;

}


20. 文件保存数据库的问题

ios 往数据库里写保存文件路径的时候,不要写全路径,因为软件更新或者重新安装沙盒路径会变


更新的流程是这样的:更新时,先在新的路径里安装新程序,然后把旧程序文件夹里的配置文件之类的文件拷贝到新的路径里去,然后删除旧程序


所以,如果数据库里保存的是绝对路径,那么软件会找不到文件。所以要保存相对路径。比如/var/mobile/applications/ECDD1B2D-E53D-4914-BDDB-F0578BADAA38/Documents/A/B/C/9A4613EA-232A-480C-9492-B34A00BE3CB6.txt
只写/A/B/C/9A4613EA-232A-480C-9492-B34A00BE3CB6.txt就好,前半部分用系统方法获取。


21. get UIView touch point

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    NSLog(@"x:%f,   y:%f", point.x, point.y);
    if (!CGRectContainsPoint(centerView.frame, point)) {
        [self removeFromSuperview];
    }

}


22. UIView一些尺寸属性

frame:origin是相对于屏幕的点的坐标,size就是其尺寸
bound: origin永远是(0,0),size也是尺寸
center: 是View的中心点,但坐标是相对于屏幕的。如果需要相对自己的中心点,则需要用bound.origin来计算
UICollectionViewCell 不能用-(id)init{},要用-(id)initWithFrame:(CGRect)frame;或者initWithCoder


autolayout
[tmpView addSubview:m_textLeftTime];
[m_textLeftTime setTranslatesAutoresizingMaskIntoConstraints:NO];


[tmpView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[m_imgClock]-0-[m_textLeftTime]"
                                                                options:0
                                                                metrics:nil
                                                                  views:NSDictionaryOfVariableBindings(m_imgClock, m_textLeftTime)]];


[tmpView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[tmpView]-(<=1)-[m_imgClock(==32)]"
                                                                options:NSLayoutFormatAlignAllCenterY
                                                                metrics:nil
                                                                  views:NSDictionaryOfVariableBindings(tmpView, m_imgClock)]];


[tmpView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[tmpView]-(<=1)-[m_textLeftTime]"
                                                                options:NSLayoutFormatAlignAllCenterY
                                                                metrics:nil
                                                                  views:NSDictionaryOfVariableBindings(tmpView, m_textLeftTime)]];
memcmp(&(GetClientID()), &(mClientID), sizeof(mClientID)) compare unsigned char or other


本文地址转载请保留:http://www.cnblogs.com/rossoneri/p/4708027.html


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: iOS内存管理版本记录如下: 1. iOS 2.0及更早版本:使用手动管理内存的方式。 2. iOS 3.0:引入了基于引用计数的自动内存管理,使用retain和release函数来增加或减少对象的引用计数。 3. iOS 5.0:引入了ARC(自动引用计数)机制,ARC会在编译时自动插入retain和release代码,减少手动管理内存的工作。 4. iOS 7.0:引入了内存诊断工具Memory Usage Report,可以监测App内存使用情况,帮助开发者优化内存管理。 5. iOS 8.0:引入了一些新的API,如NSCache和NSURLSession,使得内存管理更加方便和灵活。 6. iOS 11.0:引入了基于图片大小的UIImage渲染机制,减少了内存占用。 7. iOS 13.0:引入了叫做“Scene”的多任务环境,使得内存管理更加复杂,需要更加小心谨慎地处理内存问题。 总的来说,随着iOS版本的不断更新,内存管理的机制也在不断地完善和优化,使得iOS应用能够更加高效地使用内存,提高用户体验。 ### 回答2: iOS的内存管理是由操作系统自动管理的,在不同的版本中有所不同。 在iOS 5之前的版本中,内存管理主要依赖于手动管理引用计数(reference counting)来管理对象的生命周期。开发者需要手动调用retain和release方法来增加或减少对象的引用计数,以确保对象在不再需要时能够被正确释放。这种方式需要开发者非常谨慎地管理对象的引用,以避免内存泄漏或野指针等问题。 从iOS 5开始,iOS引入了自动引用计数(Automatic Reference Counting,ARC)的内存管理机制。ARC可以自动地插入retain、release和autorelease等方法的调用,使得开发者不再需要手动进行内存管理。开发者只需要关注对象的创建和使用,而不需要关心具体的内存管理细节。ARC减少了内存管理的工作量,提高了开发效率,并且减少了内存泄漏和野指针等问题的发生。不过,ARC并不是完全的自动化内存管理,开发者仍然需要遵循一些规则,比如避免循环引用等,以保证内存的正确释放。 随着iOS版本的不断更新,苹果不断改进和优化内存管理机制。每个新版本都带来了更好的性能和更高效的内存管理。开发者可以通过关注苹果的官方文档和开发者社区中的更新内容来了解每个版本中的具体变化和改进。 总结来说,iOS的内存管理从手动的引用计数到自动引用计数的演变,极大地简化了开发者的工作,并提高了应用的性能和稳定性。随着不断的改进和优化,iOS的内存管理会越来越高效和可靠。 ### 回答3: iOS内存管理版本记录是指苹果公司在不同版本的iOS操作系统中对于内存管理方面的改进和更新记录。随着iOS版本的不断迭代,苹果在内存管理方面进行了一系列的优化和改进,以提高系统的稳定性和性能。 首先,在早期的iOS版本中,苹果采用了手动内存管理的方式,即开发人员需要手动创建和释放内存,容易出现内存泄漏和内存溢出等问题。为了解决这些问题,苹果在iOS5版本中引入了自动引用计数(ARC)机制。ARC机制能够通过编译器自动生成内存管理代码,避免了手动管理内存带来的问题。 其次,iOS6版本引入了内存分页机制。这个机制能够将应用程序内存分成不同的页,将不常用的页置于闲置列表中,从而释放出更多的内存空间。这些闲置列表中的页能够在需要时快速恢复到内存中,减少了内存压力。 此外,iOS7版本中进一步提升了内存管理的能力。苹果在这个版本中引入了内存压缩技术,将内存中的数据进行压缩,从而提高了内存利用率。此外,iOS7还引入了资源清理功能,可以自动清理不再使用的资源,释放内存空间。 最后,在iOS13版本中,苹果进一步改进了内存管理策略。该版本中引入了后台内存优化功能,能够自动优化应用在后台运行时的内存占用,减少了后台应用对于系统内存的占用和影响。 综上所述,iOS内存管理版本记录反映了苹果在不同版本的iOS操作系统中对于内存管理方面的改进和优化。这些改进和优化使得iOS系统更加稳定和高效,并且提升了应用程序的性能和用户体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值